• 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涉及很多变量的时候,像上面那样写在同一个函数中难免会显得又长又臭。

    作者给出的优化方法是,在Reducer中直接返回一个新的字面量的state。但是这个state各个属性的值是一个reducer(state.key,action)的返回值。

    也就是说,返回的state的各个属性,都经过一个reducer的处理,如果该属性的值需要更新。则内部返回一个新属性值。如果该属性不需要更新,则内部返回原来的属性值。

    最后store获得的是响应了action的更新了的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负责列表的显示规则,顶层Reducer返回的state的各个属性的值都是一个reducer的返回值。由于内部reducer的函数名和state的属性名一致,所以可以用对象属性简写的方式:return { visibilityFilter,todos};

    要留意

    内部reducer单元中,参数state都有默认值,因为每个reducer分别更新state的不同属性,因此他们得到的state参数其实是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的工具。

  • 相关阅读:
    nodejs 文件拷贝
    MySQL linux二进制安装
    【Android工具类】验证码倒计时帮助类CountDownButtonHelper的实现
    JAVA一些基础概念
    程序猿生存定律-公司选择上的方法论
    Leetcode 第 2 题(Add Two Numbers)
    SpringMVC学习记录(五)--表单标签
    算法学习笔记(六) 二叉树和图遍历—深搜 DFS 与广搜 BFS
    CentOS 7 virt-manager 无法连接本地的hypervisor
    Android自己定义View画图实现拖影动画
  • 原文地址:https://www.cnblogs.com/alan2kat/p/7500811.html
Copyright © 2020-2023  润新知