Post on 21-Jan-2017
Mobx + React
黄英杰
Mobx 是什么
Mobx
• 基于 Observer 模式的状态管理器• 轻便、高效
Redux 已经很火了
Redux 的初始化
Redux 的初始化 : Store
Redux 的初始化 : App
Copy && Paste
Redux 如何修改 State
actions
reducers
components
我是来买手机的~~
坊间传闻:谁用 Redux 谁加班
Mobx
Mobx vs Redux
simple straightforward
Define observable state
import { observable } from 'mobx';
const store = observable({
count: 0
});
Create observer Viewimport { observer } from ‘mobx-react';@observerclass CountView extends React.Component {
render() {const { store } = this.props;return
(<button>{store.count}</button>);}
}React.render(<CountView store={store} />, document.body);
Modify State….class CountView extends React.Component {
onClick = () => this.props.store.count +=1
render() { …
return (<button onClick={this.onClick}>{store.count}</button>);
}}
Mobx VS Redux
Mission all complete!
Mobx vs Redux
• Define your state and make it observable
• Create a view that responds to changes in the State
• Modify the State
Mobx vs Redux
轻松实现高性能
Mobx vs Redux
React 高性能童话
Mobx vs Redux
Redux• 全局 setState (万恶之
源)• shouldComponentUpdat
e
• immutable.js
SCU + Immutable
• 繁琐 • 改变开发习惯
@Observer
import { observer } from ‘mobx-react';@observerclass CountView extends React.Component {
……}
@observer
• 依赖了 observable 变量的组件都加上@observer 注解
• @observer 使用越多性能越高
Mobx
高性能是如何实现的?
Mobx
摒弃全局setState
Mobx : @observer
• 自动判断哪些 state 被改变• 自动且仅更新 state 已改变的
Component
• forceUpdate ,弃用全局 setState
Mobx 基本原理
响应 State 修改
实战演练环节
• What is MobX ? https://jsfiddle.net/huangyingjie1111/r41g4f3k/
• What does @observer do ?https://jsfiddle.net/huangyingjie1111/egu3j7v0/2/
Mobx @observer
react mixins
mobx.Reaction+=@observer
forceUpdate
lifecircles
Mobx : @observer
new mobx.Reaction(name, function() { …… // Update DOM React.Component.prototype .forceUpdate.call(self) });
React 生命周期 ?
import { autorun } from ‘mobx';@observerexport default class App extends Component { componentDidMount() { autorun(this.loadMessage); } loadMessage = () => {…} …}
Mobx 优势
• Simple 、 Straightforward
• high performance
Observe 原理
• Getter / Setter
• 函数式响应编程 (FRP : functional reactive programming)
• 观察者模式
Observe 原理
Mobx 本身与 React 无关
Mobx 对比 Redux 有何优势
• 初始化代码 (boilerplates) 极少
Mobx 对比 Redux 有何优势
• 初始化代码 (boilerplates) 极少• 直接、有效、简洁
Mobx 对比 Redux 有何优势• 初始化代码 (boilerplates) 极少• 直接、有效、简洁• 轻松实现高性能
如何选择
Redux VS Mobx
• Redux = CPU + 主板 + 显卡 + 键盘 + …
• Mobx = 品牌笔记本
Redux VS Mobx
• Redux = 地毯式轰炸(全局setState )
• Mobx = 精确制导( Reactive )
兼容 IE8
• Redux: Yes
• Mobx: No
像 Vue.js ?
Mobx
It is inspired by MVVM frameworks like knockout…. vue.js
计划从 React转到 Vue.js ?
Mobx + React = 强化版Vue.js
Mobx VS Vue.js
Mobx 的简洁 + React 的虚拟 DOM > Vue.js
参考资料
• mobx getting start
• an in-deep explannation of mobx
• mobx git book