【发布时间】:2016-08-11 23:31:48
【问题描述】:
需要加载我的主要组件,如果存在具有“logged: true”对值的本地存储,请使用 react-router 重定向到“/app”。
我正在使用 react-redux,这是我的代码:
class Main extends Component {
componentWillMount(){
// Return true in redux state if localstorage is found
this.props.checkLogStatus();
}
componentDidMount(){
// redirect in case redux state returns logged = true
if(this.props.logStatus.logged){
hashHistory.push('/app');
}
}
render() {
return (
<App centered={true} className="_main">
{this.props.children}
</App>
);
}
}
我的 redux 操作:
checkLogStatus() {
// check if user is logged and set it to state
return {
type: LOGIN_STATUS,
payload: window.localStorage.sugarlockLogged === "true"
};
}
但是当组件进入componentDidMount阶段时,我的redux状态仍然没有更新。
Y 设法让这个工作通过使用:
componentWillReceiveProps(nextProps){
if (nextProps.logStatus.logged && nextProps.logStatus.logged !== this.props.logStatus.logged){
hashHistory.push('/app');
}
}
但我不确定这是最优雅的解决方案。
提前致谢!
【问题讨论】:
标签: reactjs redux lifecycle react-redux