0

js-cookie在我的React应用程序中使用过,这里我只是使用一个简单的条件来检查 cookie 是否匹配并将历史推送到以下路由,这是我的代码:

const readCookie = () => {
    let cookie = false;
    if(cookie = Cookies.get("isLogged")){
        history.push('/Homepage');
        setAuthenticated(true);
    }else{
        history.push('/');
    }
}
useEffect(() => {
    readCookie()
},[]);

但问题是,如果我有很多路线,所以我只需要编写if conditions尽可能多的现有路线来检查并推送到该特定路线,我认为这样做没有意义。所以,我只想知道有没有更简单的方法?检查 cookie 并推送到它们的路径或路线。

4

1 回答 1

0

是的,您需要创建公共和私有路由,请按照以下链接中提到的步骤操作:

https://medium.com/wesionary-team/private-and-public-routes-with-react-router-e5f814ccff2f

你也可以查看这个 repo https://github.com/thanhbinhtran93/react-router-example

于 2020-09-08T04:35:12.973 回答