【问题标题】:How does each reducer get their own part of state?每个reducer如何获得自己的状态部分?
【发布时间】:2017-01-20 00:49:06
【问题描述】:

在获得一些 React 基本概念后,我目前正在学习 Redux,我正在观看 Wes Bost 的 Learn Redux 系列视频,这是一个很棒的资源!

我有下一个问题,在那个教程中,我们有一个商店:

  • 帖子
  • 评论

评论

假设商店的每个“部分”都应该有一个“reducer”,所以我们还有“cmets”和“posts”reducer,它们在 index reducer 中与 combineReducers 合并。到目前为止一切都很好,但我的问题来了:

假设我有 Comments reducer,它接收状态和动作,但它们的状态与 state.cmets 匹配。 Posts reducer 也是如此,状态形状如何与状态的特定部分匹配?

这是来自 Redux 文档:

请注意,这些 reducer 中的每一个都在管理自己的全局状态部分。每个 reducer 的 state 参数都不同,对应于它管理的 state 部分。

【问题讨论】:

标签: reactjs redux react-redux


【解决方案1】:

combineReducer 完成了这部分的魔法。 这会调用传递的所有 reducers 对象中的每个 reducer,并构建一个具有相同形状的 state 对象。

根据他们的documentation

As your app grows more complex, you'll want to split your reducing 
function into separate functions, each managing independent parts of the
state.

The combineReducers helper function turns an object whose values are
different reducing functions into a single reducing function you can pass to 
createStore.

【讨论】:

    【解决方案2】:

    如果你问如何Redux 将reducer 与它的状态部分匹配,你可以在这里阅读Redux CombineReducers 代码找到答案:

    https://github.com/reactjs/redux/blob/master/src/combineReducers.js

    在第 147 行附近,您会看到每个 reducer 都应用于其状态键。

    【讨论】:

      【解决方案3】:

      reducer 的行为基于 action.type 。根据type,您可以更改部分状态。他们不会自动知道。例如:

      function todoApp(state = initialState, action) {
        switch (action.type) {
          case SET_VISIBILITY_FILTER:
            return Object.assign({}, state, {
              visibilityFilter: action.filter
            })
          case ADD_TODO:
            return Object.assign({}, state, {
              todos: [
                ...state.todos,
                {
                  text: action.text,
                  completed: false
                }
              ]
            })    
          default:
            return state
        }
      }
      

      【讨论】:

        【解决方案4】:

        这是 Redux 设计的一部分。 reducer 管理自己的状态。根减速器结合了各个减速器的状态。 Redux 中只有一个 store 具有组合状态。

        【讨论】:

          猜你喜欢
          • 2021-10-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-02
          • 1970-01-01
          • 2018-10-12
          • 2014-05-01
          • 2021-01-01
          相关资源
          最近更新 更多