javascript 如何确保在单击注销按钮时用户被重定向到主组件?

mnemlml8  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(87)

我不知道如何在用户退出时将其导航到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>
))}
92vpleto

92vpleto1#

使用useNavigate代替useHistory。

import { useNavigate } from "react-router-dom";
const navigate = useNavigate();

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');
                navigate("/");
            }).catch(err => {
            console.log(err);
        });
}

相关问题