无法使用 Redux 在 componentDidMount 中接收异步响应

Can't receive Async response in componentDidMount with Redux

最近我遇到了 React/Redux (Thunk) 的棘手问题:我已经使用 Action 和 Reducer 正确创建了我的 Store,在我的组件中,我触发了 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 将始终 return 在这些更改实际完成之前。

您的状态正在更新,这就是当您在 mapStateToProps 中 console.log 时它起作用的原因。

我建议设置 redux-devtools,你将能够轻松地跟踪你的 actions/state。

希望代码对你有用

componentWillReceiveProps(nextProps){  
    console.log(nextProps.inter)
}