npm 包 redux-reduced 使用教程

阅读时长 6 分钟读完

简介

redux-reduced 是一个用于简化 Redux 应用程序开发的npm包。它提供了一种更轻便,可重用的方式来定义 Redux reducer。本文将详细介绍如何使用 redux-reduced。

安装

要开始使用 redux-reduced,你需要使用 npm 安装它:

使用

定义 Redux reducer

使用 redux-reduced,您可以使用 reducer 函数的简单对象定义 redux state 的 reducer。使用这种方式,可以更轻松地定义 reducer。

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

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

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

将 Reducer 与 Store 绑定

与传统的 Redux reducer 类似,您需要将 redux-reduced reducer 与 Redux store 绑定。要做到这一点,您可以使用 Redux createStore 函数。例如:

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

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

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

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

使用 reducer 函数

使用 redux-reduced,您可以像使用传统的 reducer 一样使用我们定义的 reducer 函数:

使用 createAction

redux-reduced 还提供了一个 createAction 函数,它可以帮助您创建 redux action:

使用 createActions

redux-reduced 还提供了一个 createActions 函数,它可以帮助您创建多个 redux action。createActions 接收一个对象,其中每个键代表一个 action,值是 action 的类型。

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

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

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

使用 mergeReducers

mergeReducers 函数可以帮助您组合多个 reducer 函数。例如,我们可以将两个 reducer 函数组合:

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

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

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

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

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

结语

redux-reduced 提供了一种更轻便,可重用的方式来定义 Redux reducer。它可以提高开发效率,减少代码量。本文从安装、定义 reducer、绑定 reducer 和 store、使用 createAction 和 createActions 以及组合 reducer 函数等方面讲解了 redux-reduced 的使用方法。如有疑问,欢迎在下方评论区留言讨论。

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

纠错
反馈