【问题标题】:Redux request statuses. Reduce boilerplateRedux 请求状态。减少样板文件
【发布时间】:2020-03-31 15:50:18
【问题描述】:

我正在使用带有 react 和 redux-thunk 作为中间件的 Redux。

当我发出 http 请求时,我必须在我的 thunk 中调度三个操作。 我将使用我的身份验证示例。

这是我的行动:

export const loginSuccess = () => ({
  type: AUTH_LOGIN_SUCCESS,
})

export const loginFailure = (errorMessage) => ({
  type: AUTH_LOGIN_FAILURE,
  errorMessage,
})

export const loginRequest = () => ({
  type: AUTH_LOGIN_REQUEST,
})

这是结合了以上三个动作的thunk:

export const login = (credentials) => dispatch => {
  dispatch(loginRequest())
  const options = {
    method: 'post',
    url: `${ENDPOINT_LOGIN}?username=${credentials.username}&password=${credentials.password}`,
  }
  axiosInstance(options)
    .then(response => {
      dispatch(loginSuccess())
      dispatch(loadUser(response.data)) // I have separate action for user and separate reducer.
      window.localStorage.setItem(ACCESS_TOKEN_KEY, response.data.token)
    })
    .catch(error => {
      return dispatch(loginFailure(error))
    })
}

这是我的减速器:

const initialState = {
  pending: false,
  error: false,
  errorMessage: null,
}

export const loginReducer = (state = initialState, action) => {
  switch (action.type) {
    case AUTH_LOGIN_SUCCESS:
      return {
        ...state,
        pending: false,
        error: false,
        errorMessage: null,
      }
    case AUTH_LOGIN_FAILURE:
      const { errorMessage } = action
      return {
        ...state,
        pending: false,
        error: true,
        errorMessage,
      }
    case AUTH_LOGIN_REQUEST:
      return {
        ...state,
        pending: true,
      }
    default:
      return state
  }
}

当我发送另一个请求时,我必须做几乎完全相同的事情,例如在注销的情况下。我觉得我在重复自己很多,必须有更好的方法。

我需要知道处理此问题的最佳做法是什么。

如有任何其他更正和建议,我们将不胜感激。

【问题讨论】:

    标签: redux redux-thunk


    【解决方案1】:

    如果您正在寻找“即用型”解决方案,请查看:

    如果您正在寻找自定义解决方案,您可以创建一些工厂:

    • 减速机工厂
    • 三个动作的工厂
    • thunk 工厂
    const actions = createActions('My request name');
    const reducer = createReducer(actions);
    ...
    const thunk = createThunk(config);
    

    甚至你可以将它们组合起来:

    const { actions, reducer, thunk } = createRequestState('Name...', config);
    

    ...但这只是一个想法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-22
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 2013-03-23
      • 1970-01-01
      • 2020-10-21
      相关资源
      最近更新 更多