【问题标题】:multiple dispatch in redux actionredux 操作中的多次调度
【发布时间】:2018-05-28 20:38:52
【问题描述】:

我想从另一个动作中分派一个动作,但不能这样做。当我尝试这样做时,它无法找到 getAllUser 方法。 下面是我的动作课。

    export const myActions = {

        getAllUser() {
            return (dispatch) => {
                makeApiCall()
                    .then((response) => {
                        dispatch({
                            type: USER_SUCCESS,
                            payload: response,
                        });
                    })
                    .catch((error) => {
                        dispatch({
                            type: USER_FAILURE,
                            payload: error,
                        });
                    });
            };
        },

        addUser(user) {
            return (dispatch) => {
                makeApiCall(user)
                    .then((response) => {
                        /*
                        Need help here : 
                        wants to call above getAllUser()
                           .then(() => 
                              dispatch({
                                 type: ADD_SUCCESS,
                                 payload: response,
                              });
                            )
                        */
            };
        },
    };

我尝试了各种方法,例如,

myActions.getAllUser()
    .then((response) => 
       dispatch({
           type: ADD_SUCCESS,
           payload: response,
       });
    );

并尝试直接调度,

        const self = this;
        dispatch(self.getAllUser());
        dispatch({
            type: ADD_SUCCESS,
            payload: response,
        });

解决此问题的另一种方法是在addUser 成功之后更新reducer,而不是再次从UI 调用getAccount 以刷新结果,但只是想知道如何使用多次调度来实现这一点。

【问题讨论】:

    标签: redux react-redux


    【解决方案1】:

    您可以单独导出函数,而不是将其包装在同一个对象下:

    export const getAllUser = () => dispatch => { ... }
    
    export const addUser = () => dispatch => { 
      ... 
      dispatch(getAllUser());
    }
    

    如果需要,您仍然可以将它们全部导入:

    import * as myActions from '...';
    

    或者你可以先声明getAllUser,然后添加到myActions,但是上面的解决方案更简洁。

    const getAllUser = ...
    const myActions = {
      getAllUser,
      addUser = ... { dispatch(getAllUser()) }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-30
      • 2017-04-14
      • 2017-11-09
      • 2017-11-03
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多