redux
store 提供了三个方法用于处理数据:
- store.getState()
- store.dispatch()
- store.subscribe()
首先,用户发出 Action。
store.dispatch(action);
然后,Store 自动调用 Reducer,并且传入两个参数:当前 State 和收到的 Action。 Reducer 会返回新的 State 。
let nextState = todoApp(prevState, action);
State 一旦有变化,Store 就会调用函数。
store.subscribe(listener);
listener可以通过store.getState()得到当前状态。如果使用的是 React,这时可以触发重新渲染 View。
function listener() {
let newState = store.getState();
component.setState(newState);
}
flux
flux的最大特点是单向数据流
- 用户访问 View
- View 发出用户的 Action
- Dispatcher 收到 Action,要求 Store 进行相应的更新
- Store 更新后,发出一个”change”事件
- View 收到”change”事件后,更新页面