工做流程redux
用户在view操做发出 Action服务器
store.dispatch(action)
Store 自动调用 Reducer,而且传入两个参数:当前 State 和收到的 Action, Reducer 会返回新的 State函数
let nextState = todo(previousState, action)
State 一旦有变化,Store 就会调用监听函数spa
store.subscribe(listener) // // 设置监听函数
listener
能够经过store.getState()
获得当前状态,若是使用的是 React,这时能够触发从新渲染 View设计
function listerner() { let newState = store.getState() component.setState(newState) }
概念code
Actioncomponent
是一个对象,其中的type
属性是必须的, 用来描述当前发生的事情,改变 State 的惟一办法对象
const action = { type: 'ADD_TODO', // 名称 payload: 'content' // 携带的信息
}
stateblog
是包含全部数据的store对象的某个时间的数据集合get
import { createStore } from 'redux'
const store = createStore(fn) // 建立store对象 const state = store.getState() // 获取store对象的当前state
store.dispatch()
是 View 发出 Action 的惟一方法
import { createStore } from 'redux' const store = createStore(fn) store.dispatch({ type: 'ADD_TODO', payload: 'content' })
reducer
store 收到 action,获得一个新的 State的计算过程,是个纯函数(一样的输入,一定获得一样的输出)
const reducer = function (state, action) { // 当前state,传入的action // ... return new_state; // 返回一个新state };
store.subscribe()
设置监听函数,一旦 State 发生变化,就自动执行这个函数
import { createStore } from 'redux' const store = createStore(reducer)
store.subscribe(listener)
设计思想
Web 应用是一个状态机,视图与状态是一一对应的
全部的状态,保存在一个对象里面
适用场景
用户的使用方式复杂
不一样身份的用户有不一样的使用方式(好比普通用户和管理员)
多个用户之间能够协做
与服务器大量交互,或者使用了WebSocket
View要从多个来源获取数据
某个组件的状态,须要共享
某个状态须要在任何地方均可以拿到
一个组件须要改变全局状态
一个组件须要改变另外一个组件的状态