代码之家  ›  专栏  ›  技术社区  ›  JiteshW

减速动作多发

  •  0
  • JiteshW  · 技术社区  · 6 年前

    我想从另一个动作中调度一个动作,但不能这样做。当我试图这样做的时候,它找不到 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,然后从用户界面调用 getAccount 再次刷新结果,但只是好奇如何使用多个分派来实现这一点。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Roy Wang    6 年前

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

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

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

    import * as myActions from '...';
    

    或者你可以申报 getAllUser 先添加到 myActions 但是上面的解决方案要干净得多。

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