# 5.redux 的三个核心概念

# 1.action

  • 标识要执行行为的对象
  • 包含2个方面的属性
    • type: 标识属性, 值为字符串, 唯一, 必要属性
    • xxx: 数据属性, 值类型任意, 可选属性
  • 例子:
const action = {
  type: 'increment',
  data: 2
}
1
2
3
4
  • Action Creator (创建 Action 的工厂函数)
const increment = (number) => ({type:'increment', data:number})
1

# 2.reducer

  • 根据老的 state 和 action, 产生新的 state 的纯函数
  • 样例:
export default function counter(state=0, action) {
  switch(action.type) {
    case 'increment':
      return state + action.data
    case 'decrement':
      return state - action.data
    default:
      return state
  }
}
1
2
3
4
5
6
7
8
9
10
  • 注意:
    • 返回一个新的状态
    • 不要修改原来的状态

# 3.store

  • 将 state, action 与 reducer 联系在一起的对象
  • 如何得到此对象 ?
import { createStore } from 'redux'
import reducer from './reducers'
const store = createStore(reducer)
1
2
3
  • 此对象的功能 ?
    • getState(): 得到 state
    • dispatch(action): 分发 action, 触发 reducer 调用, 产生新的 state
    • subscribe(listener): 注册监听, 当产生了新的 state 时, 自动调用
上次更新: 2020/10/27 下午11:58:10