Redux: Concepts: Core

 20th August 2020 at 2:19pm

Redux 的核心概念就几个:

  • State:应用状态,是一个 plain object
  • Action:描述运作及其参数的 plain object
  • Reducer:一个纯函数,表示某类 action 对应的 handler,接受旧的 state 并输出处理过后的新 state

Redux 的处理过程即是,给定应用的状态数据 state,以及一套不同 action 的 reducer。后续传入的 action,会将老的 state 变成新的 state:

(previousState, action) => newState

这个理念跟函数式编程类似,即是让数据变化 predictable。具体例子看 官方文档


Reducer 相对复杂,需要重点讲解。摘录 Basic Tutorial 中的一节:

It's called a reducer because it's the type of function you would pass to Array.prototype.reduce(reducer, ?initialValue). It's very important that the reducer stays pure. Things you should never do inside a reducer:

  • Mutate its arguments
  • Perform side effects like API calls and routing transitions
  • Call non-pure functions, e.g. or Math.random().