I'm trying to implement a logic in my app where if it's the first time the user is logging in he'll see a password signup page else he'll be redirected to the dashboard. Following is the existing code:
...
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 code is not working as expected and is stuck in a loop. Any help will be appreciated.
You need to do some check in componentDidUpdate
, otherwise it'll repeatedly execute this.setState({ firstLogin })
(as it triggers componentDidUpdate
) and cause the infinite recursion.
componentDidUpdate(prevProps, prevState) {
if (!this.state.firstLogin) {
// insert code to get `firstLogin`
this.setState({ firstLogin });
};
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.