减少redux-thunk样板

And*_*gan 9 javascript reactjs redux redux-thunk redux-saga

在编写redux-thunk函数时,称为thunks,有很多样板可以很容易地被抽象掉.例如,在我们的大多数异步API调用中,我们正在执行以下操作,没有任何副作用:

export const LOGIN_REQUEST = 'my-app/auth/LOGIN_REQUEST';
export const LOGIN_RECIEVE = 'my-app/auth/LOGIN_RECIEVE';
export const LOGIN_FAILURE = 'my-app/auth/LOGIN_FAILURE';

// ... reducer code here

export function login(loginHandle, password) {
  return (dispatch, getState, api) => {
    dispatch({ type: LOGIN_REQUEST });

    api.post('/auth/login', { loginHandle, password }).then(
      response => dispatch({ type: LOGIN_RECIEVE, response }),
      error => dispatch({ type: LOGIN_FAILURE, error })
    );
  };
}
Run Code Online (Sandbox Code Playgroud)

简单!虽然因为这涵盖了我们至少70%的请求,但我确信有一种优雅的方法可以将上述代码抽象为类似的东西(伪代码):

export function login(loginHandle, password) {
  return (dispatch, getState, api) => api('POST', LOGIN_REQUEST, '/auth/login', { loginHandle, password });
}
Run Code Online (Sandbox Code Playgroud)

当我们需要检查状态和其他副作用时,我们可以回到适当的thunk.虽然在大多数情况下...我们可以减少这个?

任何优雅的想法?

Dan*_*mov 9

Redux Thunk允许您从2.1.0开始注入自定义参数.

const api = createApi() // you would write this function
const store = createStore(
  reducer,
  applyMiddleware(thunk.withExtraArgument(api))
)

// your action creator:
function fetchUser(id) {
  return (dispatch, getState, api) => {
    // you can use api here
  }
}
Run Code Online (Sandbox Code Playgroud)

在将来,如果你的thunk太复杂了,你可能想要考虑redux-sagaredux-observable.