Redux:Reducers

Posted 瓶子2333

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Redux:Reducers相关的知识,希望对你有一定的参考价值。

action只是描述了“发生了什么事情(导致state需要更新)”,但并不直接参与更新state的操作。state的更新由reducer函数执行。

其基本模式是:(state,action)=> newState

设计组件state的结构:

    在开始敲代码之前,我们要先设计好组件state的结构。我们得先明确state需要哪些变量,哪些是纯粹的数据,哪些和UI有关。用合适的结构组织起来(data类的state和UI类的state最好相互独立)。

In a more complex app, you‘re going to want different entities to reference each other. We suggest that you keep your state as normalized as possible, without any nesting. Keep every entity in an object stored with an ID as a key, and use IDs to reference it from other entities, or lists. Think of the app‘s state as a database.

如何处理action:

往reducer函数传入参数之后,根据action的type属性,函数执行对应的对state的更新。文档指出三件在reducer函数中必须避免的事情:

1.改变传入的参数。

2.执行“引发其他作用“的操作,比如调用其他api、路由跳转

3.调用”无更新无关“的函数,如Date.now()

For now, just remember that the reducer must be pure. Given the same arguments, it should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.

使用

初始化state:

在第一次调用reducer的时候,传入的state回事一个undefined,此时我们可以给它进行初始化。

 1 import { VisibilityFilters } from ‘./actions‘
 2 
 3 const initialState = {
 4   visibilityFilter: VisibilityFilters.SHOW_ALL,
 5   todos: []
 6 }
 7 
 8 function todoApp(state, action) {
 9   if (typeof state === ‘undefined‘) {
10     return initialState
11   }
12 
13   // For now, don‘t handle any actions
14   // and just return the state given to us.
15   return state
16 }

 

我们可以借助ES6的参数默认值简化代码:

1 function todoApp(state = initialState, action) {
2   // For now, don‘t handle any actions
3   // and just return the state given to us.
4   return state
5 }

最终的reducer可以是这样:

 1 function todoApp(state = initialState, action) {
 2   switch (action.type) {
 3     case SET_VISIBILITY_FILTER:
 4       return Object.assign({}, state, {
 5         visibilityFilter: action.filter
 6       })
 7     case ADD_TODO:
 8       return Object.assign({}, state, {
 9         todos: [
10           ...state.todos,
11           {
12             text: action.text,
13             completed: false
14           }
15         ]
16       })
17     default:
18       return state
19   }
20 }

记住几个地方:

*只要符合switch语句的某个case,返回的state是一个新的对象。

*匹配不到case的,default返回的是原先的state。任何意外的action都不触发state更新,可控才是最重要的。

*Object.assign是ES6的api,许多浏览器可能并不原生支持,开发时记得安装插件 Babel plugin。另,assign第一个参数必须是空对象;也可以用 对象扩展运算符{...state,...update}。

*switch语句不是必须的,reducer内部的结构完全由自己设计

分解(解构)reducer:

当我们的state涉及很多变量的时候,像上面那样写在同一个函数中难免会显得又长又臭。

作者给出的优化方法是,根据action的type属性,将state的更新划分为几个类型,每种类型的更新任务由对应的reducer小单元来处理。也即将app的Reducer解耦为若干个小reducer,此时Reducer只负责action类型判断和任务分配,小reducer负责返回state需要更新的属性

看下面的例子:

 1 function todos(state = [], action) {
 2   switch (action.type) {
 3     case ADD_TODO:
 4       return [
 5         ...state,
 6         {
 7           text: action.text,
 8           completed: false
 9         }
10       ]
11     case TOGGLE_TODO:
12       return state.map((todo, index) => {
13         if (index === action.index) {
14           return Object.assign({}, todo, {
15             completed: !todo.completed
16           })
17         }
18         return todo
19       })
20     default:
21       return state
22   }
23 }
24 
25 function visibilityFilter(state = SHOW_ALL, action) {
26   switch (action.type) {
27     case SET_VISIBILITY_FILTER:
28       return action.filter
29     default:
30       return state
31   }
32 }
33 
34 function todoApp(state = {}, action) {
35   return {
36     visibilityFilter: visibilityFilter(state.visibilityFilter, action),
37     todos: todos(state.todos, action)
38   }
39 }

这段代码结构很清晰,todos函数负责管理事件的添加和‘是否完成’的标记,visibilityFilter负责列表的显示规则,真正统筹state的是todoApp这个顶层Reducer。

要留意

小reducer单元中,参数state都有默认值,因为每个reducer分别执行不同的更新任务,因此他们得到的往往是state的一部分属性,这部分属性和该次更新的类型有关。他们返回的值是新state的一部分。

顶层Reducer才是返回新state的地方。

另外,Redux提供了一个工具 combineReducers()来帮助我们实现上面这种分解reducer功能的逻辑:

 1 import { combineReducers } from ‘redux‘
 2 
 3 const todoApp = combineReducers({
 4   visibilityFilter,
 5   todos
 6 })
 7 
 8 export default todoApp
 9 
10 等价于
11 
12 export default function todoApp(state = {}, action) {
13   return {
14     visibilityFilter: visibilityFilter(state.visibilityFilter, action),
15     todos: todos(state.todos, action)
16   }
17 }

就是一个生成Reducer的工具。

 

以上是关于Redux:Reducers的主要内容,如果未能解决你的问题,请参考以下文章

javascript Redux REDUCERS:strukturaplikówinanazewnictwo

React.js/Redux:Reducers 中的 setInterval 和 clearInterval

Redux reducers——改变深度嵌套状态

[Functional Programming ADT] Combine Multiple State ADT Based Redux Reducers

[Recompose] Add Local State with Redux-like Reducers using Recompose

React之react-redux的使用与项目的打包