【问题标题】:redux: nested reducer access another store sectionredux:嵌套减速器访问另一个存储部分
【发布时间】:2017-01-06 16:28:56
【问题描述】:

我使用 redux 的 combineReducers() 辅助函数来组合两个 reducer,如下所示:

const rootReducer = combineReducers({
  user: userReducer,
  accounts: accountsReducer
})

我知道每个reducer 只能修改它分配到的商店的一部分,在这种情况下是“用户”和“帐户”。

如何从我的帐户缩减程序中修改商店的“用户”部分?

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    你不能。

    您可以在两个 reducer 中监听相同的操作,或者如果您需要根据帐户状态的更新来更新用户状态,那么您可以使用 Redux thunks - https://github.com/gaearon/redux-thunk

    const action = () => (dispatch, getState) => {
      // dispatch action that accounts reducer listens to
      dispatch({
        type: 'SOME_ACTION'
      })
    
      // get the new accounts state
      let { accounts } = getState()
    
      // dispatch action that user reducer listens to, passing the new accounts state
      dispatch({
        type: 'ANOTHER_ACTION',
        payload: {
          accounts
        }
      })
    }
    
    // call with
    dispatch(action())
    

    【讨论】:

    • "在两个 reducer 中监听相同的操作" - 这是否意味着我可以做这样的事情: dispatch action like {type: 'SET_ACTIVE_ACCOUNT' , data: data} 然后在accounts reducer 中处理设置活动帐户的操作并在用户减速器中监听相同的事件并修改商店的某些部分?
    • @GilbertNwaiwu 是的,每一个 reducer 都会在动作被调度时被调用。您可以从 1 个操作更新多个减速器的状态(前提是您在操作的有效负载中拥有所需的所有数据)
    • 好的。谢谢(你的)信息。我想我在某个地方读到过。调用所有 reducer,并合并它们的存储输出。
    猜你喜欢
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 2016-06-04
    • 2020-07-07
    • 1970-01-01
    相关资源
    最近更新 更多