redux
是一套state
流的处理机制。redux
主要有
三要素
:segmentfault
store 【长官】 管理状态,给某个士兵发命令app
action 【命令】 一种长官和士兵之间沟通的方式函数
reducer 【士兵】 执行命令,并反馈给长官学习
主要有
三层数据流
:ui
长官
下达命令
并把当前任务状态
告诉士兵
=>spa
士兵
执行命令反馈任务状态
给长官
=>3d
长官
更新任务状态
日志
全部状态都在一颗惟一的state
树种code
Action经过type,代表了我要修改什么东东,至关于一个指令
{ type: 'ADD_TODO', text: 'Build my first Redux app' }
Action通常经过Action建立函数生成
// actions.js export default function todos(type, a, b) { return { type, a, b } }
// reducers.js export default function todoApp(state, action) { switch (action.type) { case 'add': return Object.assign({}, state, { result : action.a + action.b }) case 'sub': return Object.assign({}, state, { result : action.a - action.b }) default: return state } }
维持应用的 state;
提供 getState()
方法获取 state
;
提供 dispatch(action)
方法更新 state
;
经过 subscribe(listener)
注册监听器;
经过 subscribe(listener)
返回的函数注销监听器。
能够说store是真正的state管理者,其余的,如action
是命令,reducer
是执行命令的士兵。
// store.js import { createStore } from 'redux'; import { todos } from './actions'; import { todoApp } from './reducers.js'; let store = createStore(todoApp); // 打印初始状态 console.log(store.getState()) // 每次 state 更新时,打印日志 // 注意 subscribe() 返回一个函数用来注销监听器 let unsubscribe = store.subscribe(() = console.log(store.getState()) ) // 发起一系列 action store.dispatch(todos('add', 100, 99)); store.dispatch(todos('sub' ,100, 99)); // 中止监听 state 更新 unsubscribe();