Reactjs componentDidMount中未识别componentWillMount中的Redux状态更改?
需要加载我的主组件,如果存在对值为“logged:true”的localstorage,请使用react路由器重定向到“/app” 我正在使用react redux,以下是我的代码:Reactjs componentDidMount中未识别componentWillMount中的Redux状态更改?,reactjs,redux,lifecycle,react-redux,Reactjs,Redux,Lifecycle,React Redux,需要加载我的主组件,如果存在对值为“logged:true”的localstorage,请使用react路由器重定向到“/app” 我正在使用react redux,以下是我的代码: class Main extends Component { componentWillMount(){ // Return true in redux state if localstorage is found this.props.checkLogStatus(); } compo
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>
);
}
}
但是当组件进入componentDidMount阶段时,我的redux状态仍然没有更新
Y通过使用以下方法使其正常工作:
componentWillReceiveProps(nextProps){
if (nextProps.logStatus.logged && nextProps.logStatus.logged !== this.props.logStatus.logged){
hashHistory.push('/app');
}
}
但我不确定这是最优雅的解决方案
提前谢谢 使用
组件WillReceiveProps
是一种方法,因为您的logStatus对象是作为正在更改的道具传入的
有一种更优雅的方法,使用它可以分派函数(它接收dispatch
作为参数,而不是对象操作。然后,您可以将该函数包装在承诺中,并在组件willmount
中使用它
在您的操作文件中:
updateReduxStore(data) {
return {
type: LOGIN_STATUS,
payload: data.logInCheck
};
}
validateLocalStorage() {
...
}
checkLogStatus() {
return function(dispatch) {
return new Promise((resolve, reject) => {
validateLocalStorage().then((data) => {
if (JSON.parse(data).length > 0) {
dispatch(updateReduxStore(data));
resolve('valid login');
} else {
reject('invalid login');
}
});
});
};
}
然后在组件中:
componentWillMount() {
this.props.checkLogStatus()
.then((message) => {
console.log(message); //valid login
hashHistory.push('/app');
})
.catch((err) => {
console.log(err); //invalid login
});
}
Redux thunk中间件是为此类用例而设计的。使用组件WillReceiveProps是一种方法,因为您的logStatus对象是作为正在更改的道具传入的 有一种更优雅的方法,使用它可以分派函数(它接收
dispatch
作为参数,而不是对象操作。然后,您可以将该函数包装在承诺中,并在组件willmount
中使用它
在您的操作文件中:
updateReduxStore(data) {
return {
type: LOGIN_STATUS,
payload: data.logInCheck
};
}
validateLocalStorage() {
...
}
checkLogStatus() {
return function(dispatch) {
return new Promise((resolve, reject) => {
validateLocalStorage().then((data) => {
if (JSON.parse(data).length > 0) {
dispatch(updateReduxStore(data));
resolve('valid login');
} else {
reject('invalid login');
}
});
});
};
}
然后在组件中:
componentWillMount() {
this.props.checkLogStatus()
.then((message) => {
console.log(message); //valid login
hashHistory.push('/app');
})
.catch((err) => {
console.log(err); //invalid login
});
}
Redux thunk中间件就是为这种用例而设计的