如何在 Redux 中使用多个 Reducer

阅读时长 5 分钟读完

什么是复合 Reducer

在 Redux 应用中,Reducer 是用来处理应用中不同 state 的函数。Reducer 接收两个参数,第一个参数是当前的 state,第二个参数是要执行的 action。Reducer 返回新的 state,更新应用中的状态。

然而,在实际应用中,我们可能需要处理多个 state,每个 state 对应不同的页面或功能。这时,单个 Reducer 的功能会变得受限,因为单个 Reducer 可能变得过于复杂。Redux 提供了复合 Reducer 的方式来解决这个问题。

复合 Reducer 即 combineReducer,它是 Redux 提供的一个工具函数,用于将多个 Reducer 合成一个父级 Reducer,方便管理应用的不同状态。

如何使用

我们可以通过下面的方式使用 combineReducers() 函数:

combineReducers() 函数接收一个对象作为参数,这个对象的 key 是 state 项的名称,value 是对应的 reducer 函数。最终,combineReducers() 函数会返回一个新的函数,这个函数为整个应用的 state 服务。

假设现在我们有一个简单的 Count 应用,我们希望将 Count 页面和 Message 页面的状态分开管理,那么可以如下实现:

-- -------------------- ---- -------

-- ---------------

----- ------------ - ------ - - ------ - -- ------- -- -
  ------ ------------- -
    ---- ------------
      ------ - ------ ----------- - - --
    ---- ------------
      ------ - ------ ----------- - - --
    --------
      ------ ------
  -
--

------ ------- -------------

-- -----------------

----- -------------- - ------ - - -------- -- -- ------- -- -
  ------ ------------- -
    ---- --------------
      ------ - -------- -------------- --
    --------
      ------ ------
  -
--

------ ------- ---------------

-- --------------

------ - --------------- - ---- --------
------ ------------ ---- -----------------
------ -------------- ---- -------------------

----- ----------- - -----------------
  ------ -------------
  -------- ---------------
---

------ ------- ------------
展开代码

在组件中使用

在组件中,我们可以使用 react-redux 提供的 connect() 函数来连接应用的 state 和组件的 props,示例代码如下:

-- -------------------- ---- -------

------ ----- ---- --------
------ - ------- - ---- --------------

----- ----- ------- --------------- -
  -------- -
    ----- - ------ ---------- --------- - - -----------

    ------ -
      -----
        ------- ------------------------------
        --------------------
        ------- ------------------------------
      ------
    --
  -
-

----- --------------- - ----- -- --
  ------ ------------------
---

----- ------------------ - -
  ---------- -- -- -- ----- ----------- ---
  ---------- -- -- -- ----- ----------- ---
--

------ ------- ------------------------ ---------------------------
展开代码

总结

使用 Redux 管理应用状态是一个不错的选择。使用 combineReducer,我们可以将多个 Reducer 管理的 state 组合在一起,方便管理应用状态。

在使用 Redux 的时候,建议遵循一个 Reducer 管理一个 state 的原则,这样可以保证代码的简洁,易于维护。同时也要注意使用好 Redux 提供的工具函数,如 combineReducers 和 connect,它们会大大提高我们的工作效率。

完整示例代码请参考:https://github.com/kaysonwu/react-redux-tutorial

来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/646dcb58968c7c53b0c6bfa4

纠错
反馈

纠错反馈