【问题标题】:How to call redux action after success of another action?如何在另一个动作成功后调用 redux 动作?
【发布时间】:2017-04-12 00:51:27
【问题描述】:

所以我有一个 auth 相关的减速器设置如下:

export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case LOAD:
      return {
        ...state,
        loading: true,
      }
    case LOAD_SUCCESS:
      return {
        ...state,
        loading: false,
        loaded: true,
        jwt: action.jwt,
      }
    case LOAD_FAIL:
      return {
        ...state,
        loading: false,
        loaded: false,
        error: true,
        errorMessage: action.error,
      }
    case LOGIN:
      return {
        ...state,
        loaded: false,
        loggingIn: true,
      }
    case LOGIN_SUCCESS:
      return {
        ...state,
        loaded: true,
        loggingIn: false,
        jwt: jwtDecode(action.result.token),
      }
    case LOGIN_FAIL:
      return {
        ...state,
        loggingIn: false,
        user: null,
        error: true,
        errorMessage: action.error,
      }
    case LOGOUT:
      return {
        ...state,
        loggingOut: true,
      }
    case LOGOUT_SUCCESS:
      return {
        ...state,
        loggingOut: false,
        user: null,
        jwt: null,
      }
    case LOGOUT_FAIL:
      return {
        ...state,
        loggingOut: false,
        error: true,
        errorMessage: action.error,
      }
    default:
      return state
  }
}

其中 LOAD 是加载先前存储的(cookie 或 JWT)身份验证,而 LOGIN/LOGOUT 是不言自明的。

我需要在成功加载或登录后触发一些进一步的操作。

我想执行一个 GET 请求来获取有关用户的一些私有数据,这些数据只有在登录后才可用,并将这些私有数据存储在 redux 存储中以供应用程序的各个部分使用。我该怎么做?

【问题讨论】:

  • 你读过 Redux 文档中关于 Async Actions 的部分吗?这很好地解释了它。

标签: reactjs functional-programming redux react-redux flux


【解决方案1】:

您应该使用async actions 来完成此操作。

您必须编写异步操作创建器,它将调用多个操作。

类似的东西:

function multipleAtions() {
 return (dispatch) => { 
   dispatch(load_action);
   return fetch(`http://some_request_here`)
          .then(() => dispatch(another_action);
 }
}

【讨论】:

    猜你喜欢
    • 2019-02-14
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    相关资源
    最近更新 更多