简体   繁体   English

如何检查用户是否登录然后重定向?

[英]How to check if user logged and then redirect?

I have tried all answers I could find, this is my routing: 我尝试了所有可以找到的答案,这是我的路线:

const loggedIn = !!localStorage.getItem('token');

const Routes = () => (
    <div>
        <Switch>
            <Route exact path="/" render={() => (
                !loggedIn ? (
                    <Redirect to="/login" />

                ) : (
                    <Redirect to="/welcome" />
                )
            )}/>
</Switch>
    </div>
);

export default Routes;

However, it is still not working.. I am getting an error on other container: 但是,它仍然无法正常工作。.我在其他容器上收到错误消息:

menuContainer.js:10 Uncaught TypeError: Cannot read property 'id' of null menuContainer.js:10未捕获的TypeError:无法读取null的属性“ id”

constructor(props) {
        super(props);
        this.state = {
            userId: JSON.parse(localStorage.getItem('logged')).id,
            loginRole: localStorage.getItem('loggedRole')
        }
    };

What am I doing wrong here? 我在这做错了什么?

Thanks! 谢谢!

EDIT: I don't have any id if user is not logged in. That's the whole point. 编辑:如果用户未登录,我没有任何ID。这就是重点。 :) If user is not logged in, it should redirect back to /login. :)如果用户未登录,则应重定向回/ login。

首先,您需要在localStorage中设置项目

localStorage.setItem('name', value )

I'm not sure how do u set the localStorage object before. 我不确定您之前如何设置localStorage对象。

var userobj = { id : 12 }

localStorage.setItem('logged',JSON.stringify(userobj))

then try getting it like JSON.parse(localStorage.getItem('logged')).id; //return 12 然后尝试像JSON.parse(localStorage.getItem('logged')).id; //return 12一样获取它 JSON.parse(localStorage.getItem('logged')).id; //return 12

This is how it needs to be done. 这就是需要做的事情。 If the token which u receive has the id, u have to manually set it before getting it :) 如果您收到的token具有ID,则必须在获取它之前手动设置它:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM