Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数据流框架学习(一) #4

Open
zhuping opened this issue Feb 27, 2018 · 0 comments
Open

数据流框架学习(一) #4

zhuping opened this issue Feb 27, 2018 · 0 comments

Comments

@zhuping
Copy link
Owner

zhuping commented Feb 27, 2018

Flux介绍

Flux作为一种设计模式,以单向数据流的方式补充了 React 视图组件。主要分成三个部分:

  • Dispatcher
    • 作为分发器,把每个 action 动作通知到所有 store
  • Store
    • 存储 state 状态,并且对不同的 action 做出对应的操作
  • View
    • 理解为顶层的 controller view ,监听 store 状态是否改变,让它所管辖的子 view 渲染新的 state

如何工作?

初始化阶段
  1. 所有 store 注册到 dispatcher 中,并告知 dispatcher 一旦有 action 产生就要通知它
  2. controller view 从 store 中获取最新的 state 状态,同时监听 store 状态值的变化
数据流产生
  1. 用户行为操作,view 产生一个 action 操作,通过 dispatcher 分发器通知所有 store
  2. store 自行判断是否对这个 action 做出响应,更新 state
  3. 一旦 store 更新 state 完毕,就会告知订阅了该 store 的 controller view
  4. 这些 controller view 拿到最新的 state 之后,将会让它所管辖的子 view 渲染新的 state

结合代码理解

基于 https://github.com/facebook/flux/tree/2.0.1/examples/flux-todomvc

// https://github.com/facebook/flux/blob/2.0.1/examples/flux-todomvc/js/stores/TodoStore.js#L122
AppDispatcher.register(function(payload) {
  ...
})
// https://github.com/facebook/flux/blob/2.0.1/examples/flux-todomvc/js/components/TodoApp.react.js#L35
getInitialState: function() {
  return getTodoState();
},

componentDidMount: function() {
  TodoStore.addChangeListener(this._onChange);
},
// https://github.com/facebook/flux/blob/2.0.1/examples/flux-todomvc/js/dispatcher/AppDispatcher.js#L24
this.dispatch({
  source: 'VIEW_ACTION',
  action: action
});
// https://github.com/facebook/flux/blob/2.0.1/examples/flux-todomvc/js/stores/TodoStore.js#L126
switch(action.actionType) {
  ...
}
// https://github.com/facebook/flux/blob/2.0.1/examples/flux-todomvc/js/stores/TodoStore.js#L173
TodoStore.emitChange();
// https://github.com/facebook/flux/blob/2.0.1/examples/flux-todomvc/js/components/TodoApp.react.js#L66
_onChange: function() {
  this.setState(getTodoState());
}

参考

图解 Flux

深入浅出React+Redux

如何理解 Facebook 的 flux 应用架构?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant