我不知道如何在用户退出时将其导航到Home
组件。我已经测试过了,这个API工作正常。
但是,我不确定如何在当前上下文中使用logout
方法,以便用户成功注销并返回到Home
组件。
当前行为不正确,因为当我单击Logout
时,Grid
组件变为空白,而不是重定向到Home
组件。如何修复此问题?
这里是一个应用程序. js:
const App = () => {
return (
<>
<Router>
<Switch>
<Route exact path="/" component={Home} />
<ProtectedRoute path="/gallery" component={Grid} />
</Switch>
</Router>
</>
);
}
下面是Navbar.js:
import { Link as RouterLink } from "react-router-dom";
import { useHistory } from "react-router-dom";
const settings = ['Profile', 'Account', 'Gallery', 'Logout'];
let authToken = localStorage.getItem('token');
const settingsSelection = (settings) => {
switch (settings) {
case "Logout":
return "/";
}
};
const logout = () => {
const headers = {
"Accept": 'application/json',
"Authorization": `Bearer ${authToken}`
};
const data = "";
axios.post('http://127.0.0.1:8000/api/logout', data, {headers})
.then(resp => {
localStorage.removeItem('token');
history.push('/');
}).catch(err => {
console.log(err);
});
}
{settings.map((setting) => (
<MenuItem key={setting} onClick={handleCloseUserMenu}>
<Typography
textAlign="center"
component={RouterLink}
to={settingsSelection(setting)}
// onClick={logout()}
>
{setting}
</Typography>
</MenuItem>
))}
1条答案
按热度按时间92vpleto1#
使用useNavigate代替useHistory。