【问题标题】:redux-thunk pass dispatch to another function?redux-thunk 将调度传递给另一个函数?
【发布时间】:2017-02-03 08:50:53
【问题描述】:

我目前有想使用函数组合的场景:

const funcTwo = (status, response) =>
  (dispatch) => {
    if (response.error) {
      dispatch({ type: TOKEN_FAILURE });
      dispatch(notificationShow('ERROR', response.error.message));
    } else {
      dispatch({ type: TOKEN_SUCCESS, payload: response.id });
    }
  };

export const funcOne = target =>
  (dispatch) => {
    dispatch({ type: TOKEN_REQUEST });
    Helper.createToken(target, funcTwo);
  };

由于funcTwo 没有在任何类型的connect() 中使用它,我目前面临调度无法在funcTwo 中工作的问题,但我想知道是否有可能以某种方式将调度传递给它?

【问题讨论】:

    标签: javascript reactjs redux redux-thunk


    【解决方案1】:

    创建两个本身是 thunk 的函数,并将响应处理逻辑移至第一个。你的辅助函数应该返回一个Promise,这样你就可以链接你的成功/错误处理程序。

    这个想法是一个 thunk 可以调度多个动作,其中任何一个或全部都可以是另一个 thunk 本身。

    伪代码:

    export function requestToken(target){
      return (dispatch) => {
         dispatch({ type: TOKEN_REQUEST })
         Helper.createToken(target)
         .then(
            response => {
              dispatch({ 
                type: TOKEN_REQUEST_SUCCESS, 
                payload: response.id
              })
            },
            //your createToken failure handler
            error => {
              dispatch(yourErrorActionCreator(err))
            }
         )
      }
    

    【讨论】:

      【解决方案2】:

      是的!它是。

      const funcTwo = (status, response, dispatch) =>
      () => {
          if (response.error) {
            dispatch({ type: TOKEN_FAILURE });
            dispatch(notificationShow('ERROR', response.error.message));
          } else {
            dispatch({ type: TOKEN_SUCCESS, payload: response.id });
          }
        };
      
      export const funcOne = target =>
        (dispatch) => {
          dispatch({ type: TOKEN_REQUEST });
          Helper.createToken(target, (status, response) => funcTwo(status, response, dispatch ));
        };
      

      【讨论】:

        猜你喜欢
        • 2019-04-01
        • 2018-06-29
        • 2020-03-25
        • 1970-01-01
        • 2019-07-25
        • 2023-03-23
        • 2012-09-25
        • 2020-10-03
        相关资源
        最近更新 更多