最近我遇到了React / Redux(Thunk)的一个棘手问题:我已经正确地创建了我的Store with Action和Reducer,在我的Component中我触发了componentDidMount方法中的Async函数以更新状态,但是状态没有似乎在改变,虽然它在componentDidUpdate和mapStateToProps函数中确实发生了变化!为什么?这是我的代码:
export const getAllInterventions = () => {
return dispatch => {
dispatch(getAllDataStart());
axios.get('/interventions.json')
.then(res => {
dispatch(getAllDataSuccess(res.data));
})
.catch(err => {
dispatch(getAllDataFail(err));
});
};
我的减速机:
case actionTypes.GET_ALL_INTERVENTIONS_SUCCESS:
return {
...state,
interventions: interventions: action.interventions
};
我的组件:
componentDidMount() {
this.props.getAllInterventions();
console.log('DidMount: ', this.props.inter); /*Empty Array Or Undefined */
}
const mapStateToProps = state => {
console.log('mapStateToProps', state);
return {
inter: state.interventions,
error: state.error
};
您的操作和状态更改都是异步的,在完成这些更改之前将始终返回console.log
。
您的状态正在更新,这就是为什么它在mapStateToProps中console.log
时有效。
我建议设置redux-devtools,你将能够轻松跟踪你的行动/状态。
我希望代码对您有用
componentWillReceiveProps(nextProps){
console.log(nextProps.inter)
}