redux-thunk 将调度传递给另一个函数?

redux-thunk pass dispatch to another function?

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

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);
  };

我目前面临 dispatch 在 funcTwo 中不起作用的问题,因为它没有在任何类型的 connect() 中使用,但我想知道是否可以将 dispatch 传递给它不知何故?

是的!这是。

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 ));
  };

创建两个本身就是thunk的函数,将响应处理逻辑移到第一个。你的辅助函数应该 return a 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))
        }
     )
  }