我正在尝试更新redux状态,我遇到的问题是当使用多个操作执行onclick函数时,mapStateToProps没有得到更新。我知道动作是异步运行的,这就是为什么状态没有按时更新的原因。有没有办法解决这个问题

代码示例

当执行OnClickFunction时,getCase操作将this.props.filters.active_case_page作为页码
和nexPage操作会更改active_case_page索引,但是这里的问题是执行getCase操作时this.props.getCases仍然具有this.props.filters.active_case_page的旧值。

OnClickFunction = () => {
    this.props.nextPage(this.props.filters.active_case_page);
    this.props.getCases(this.props.filters.active_case_page,'All','dateCreated',false,null,'5a9ee9fa88406eeeebabbd1f')
}

function mapStateToProps(state){
    return{
        filters: state.doctors.filters,
    }
}

function mapDispatchToProps(dispatch){
    return bindActionCreators({

        nextPage:nextPage,
        getCases:getCases
    },dispatch)
}

export function nextPage(){

    return{
        type:"NEXT_PAGE"
    }
}

export function getCases(pageNum,filterType,filterOption,isSearchOn,searchText,doctor_id){

    return function(dispatch){
        axios.get("/api/getCases/"+pageNum+"/"+filterType+"/"+filterOption+"/"+isSearchOn+"/"+searchText+"/"+doctor_id)
            .then(function(response){
                dispatch({type:"GET_CASES",payload:response.data});
            })
            .catch(function(err){
                dispatch({type:"GET_CASES_REJECTED",payload:err});
            })
    }
}

export function doctorsReducers(state={
    customer_cases:[],
    filters:{
        active_case_page:0,
        selected_cases_filter:'dateCreated',
        filter_options: 'All',
        isCaseSearchOn:false,
        search_cases:'',
    }

}, action){
    switch(action.type){

        case "NEXT_PAGE":
        // return the state and copy of boos array from state
            return {
                ...state,
                filters:{
                    ...state.filters,
                    active_case_page:state.filters.active_case_page+1,
                }

            }
        break;

        case "GET_CASES":
        // return the state and copy of boos array from state
            return {
                ...state,
                customer_cases:[...action.payload[0]],
            }
        break;

    }
    return state;
}

最佳答案

现在,您已经使问题更清楚了,看起来您正在寻找一种方法,一旦第一个操作完成,就可以分派第二个操作。

我可能会以这种方式使用componentWillReceiveProps

componentWillReceiveProps(nextProps){
    const {filters: {active_case_page}, getCases} = nextProps;
    if (active_case_page !== this.props.filters.active_case_page){
      getCases(active_case_page,'All','dateCreated',false,null,'5a9ee9fa88406eeeebabbd1f'
    }
}


但是海事组织,整个模式不是很好。
我会将两个动作放到一个动作中,然后将所有动作放在一起(除非您的问题中缺少功能,因为当前我看不到将这个动作分为两个动作的任何理由)

07-24 09:38
查看更多