显示登录页面的应用程序,然后重定向到主页



请耐心等待,因为这是我的第一个应用程序,所以我不是很有信心。1-我的问题是,当进入我的应用程序时,我必须显示登录按钮(我没有注册表(,我可以从谷歌获得代币。这样,我就可以登陆/主页,在应用程序中,侧边栏必须显示在每个页面上2使用我得到的令牌,我必须在数据库中检查用户是否是管理员。根据这些信息,我可以显示或隐藏一些页面/组件。

我实现的结构就是这个

function App() {
const [token, setToken] = useState(false);
const history = useHistory();
if (!token) {
return (
<Login
setToken={setToken}
history={history}
/>
);
}
return (
<>
<Router>
<Sidebar />
<Switch>
<Route exact path='/home'>
<Home />
</Route>
<Route exact path='/departments'>
<DepartmentTable />
</Route>
<Route exact path='/users/1'>
<UserTable />
</Route>
<Route extact path='/types'>
<KindTable />
</Route>
<Route exact path='/devices/1'>
<DeviceTable />
</Route>
<Route exact path='/test'>
<Test />
</Route>              
</Switch>
</Router>
</>
);
}

在登录组件中,我使用GoogleLogin库

const Login = ({ setToken, setNotAuthenticated, history }) => {
const responseSuccGoogle = async (response) => {
setToken(true);
try {
const { data } = await axios.post(
"https:xxxx",
{ token: response.tokenId }
);
localStorage.setItem("refreshToken", data.refresh_token);
localStorage.setItem("accessToken", data.access_token);
history.replace("/home");
console.log(localStorage.getItem("accessToken"));
} catch (error) {
console.log(error);
}
};
const responseFailGoogle = (response) => {
console.log(response);
};
return (

<GoogleLogin
className='gbutton'
clientId='xxxx'
buttonText='Login with Google'
onSuccess={responseSuccGoogle}
onFailure={responseFailGoogle}
cookiePolicy={"single_host_origin"}
/>
);
};

我得到的是,在成功登录时,在设置令牌后,我进入应用程序,但不在/主页中。我怎样才能做到这一点?(第一个问题(此外,如果我在浏览器中键入http://localhost:3000/home,或/departments我看到登录页面,登录后,我被重定向到那里。事实上,在登录之前,我不应该在那个地址看到任何东西:(

在登录组件中,无论是否从axios请求获得{data}history.replace("/home");始终运行。

替换为:

if(data){
setToken(true);
history.replace("/home");
}

最新更新