Javascript 第一个登录逻辑在React应用程序中不起作用
我试图在我的应用程序中实现一个逻辑,如果用户是第一次登录,他将看到一个密码注册页面,否则他将被重定向到仪表板。现行守则如下:Javascript 第一个登录逻辑在React应用程序中不起作用,javascript,reactjs,Javascript,Reactjs,我试图在我的应用程序中实现一个逻辑,如果用户是第一次登录,他将看到一个密码注册页面,否则他将被重定向到仪表板。现行守则如下: ... constructor() { super() this.state = {firstLogin: null} } componentWillMount = () => { if (localStorage.getItem('isLogged') ) this.props.history.push('/dashboard');
...
constructor() {
super()
this.state = {firstLogin: null}
}
componentWillMount = () => {
if (localStorage.getItem('isLogged') )
this.props.history.push('/dashboard');
};
componentDidUpdate = () => {
try {
const firstLogin = JSON.parse(localStorage.getItem('clientUser')).first_login;
this.setState({firstLogin});
}
catch (e) {
}
if (localStorage.getItem('isLogged')) {
if (this.state.firstLogin)
this.setState({firstLogin: true});
else
this.props.history.push('/dashboard')
}
};
render() {
return (
{this.state.firstLogin ?
<div>
//account setup page
</div> :
<div>
//login page
</div>}
)
}
。。。
构造函数(){
超级()
this.state={firstLogin:null}
}
组件将装入=()=>{
if(localStorage.getItem('isLogged'))
this.props.history.push('/dashboard');
};
componentDidUpdate=()=>{
试一试{
const firstLogin=JSON.parse(localStorage.getItem('clientUser')).first\u login;
this.setState({firstLogin});
}
捕获(e){
}
if(localStorage.getItem('isLogged')){
if(this.state.firstLogin)
this.setState({firstLogin:true});
其他的
this.props.history.push(“/dashboard”)
}
};
render(){
返回(
{this.state.firstLogin?
//帐户设置页
:
//登录页面
}
)
}
此代码未按预期工作,并卡在循环中。任何帮助都将不胜感激。您需要执行一些签入
componentdiddupdate
,否则它将重复执行此.setState({firstLogin})
(当它触发componentdiddupdate
)并导致无限递归
componentDidUpdate(prevProps, prevState) {
if (!this.state.firstLogin) {
// insert code to get `firstLogin`
this.setState({ firstLogin });
};
}