redux

image.png
store 提供了三个方法用于处理数据:

  • store.getState()
  • store.dispatch()
  • store.subscribe()
  1. 首先,用户发出 Action。

    1. store.dispatch(action);
  2. 然后,Store 自动调用 Reducer,并且传入两个参数:当前 State 和收到的 Action。 Reducer 会返回新的 State 。

    1. let nextState = todoApp(prevState, action);
  3. State 一旦有变化,Store 就会调用函数。

    1. store.subscribe(listener);
  4. listener可以通过store.getState()得到当前状态。如果使用的是 React,这时可以触发重新渲染 View。

    1. function listener() {
    2. let newState = store.getState();
    3. component.setState(newState);
    4. }

    WechatIMG13.jpeg

flux

flux的最大特点是单向数据流
image.png

  1. 用户访问 View
  2. View 发出用户的 Action
  3. Dispatcher 收到 Action,要求 Store 进行相应的更新
  4. Store 更新后,发出一个”change”事件
  5. View 收到”change”事件后,更新页面