MobX是一个简单有效的状态管理库,以派生(derive)的概念为核心,以观察者模式为手段,达到了修改数据自动更新界面等目的
本系列前几篇文章演示了不用react和es6/babel等如何方便的修改传统的es5代码,但MobX也为react提供了方便的包装方法,本篇还是引入一些jsx语法等,展示利用mobx-react包改善React组件管理状态的流程
[V]. 用 observer()
使React组件自动反应
- mobx-react由独立的包 https://github.com/mobxjs/mobx-react 提供
- 核心方法是
mobxReact.observer(reactComp)
,作用就是将React组件的render()方法包装一层mobx.autorun()
- 除了使组件自身的state可观察化,较好的做法是传递一个可观察的props给组件,使组件成为一个无状态(stateless)组件
- componentWillReact()钩子方法会在数据改变时被调用
<script src="https://unpkg.com/mobx/lib/mobx.umd.js"></script>
<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
<script src="https://unpkg.com/mobx-react"></script><div id="ctn1"></div>
代码语言:javascript复制var myData = mobx.observable({time:0});setInterval(function(){
myData.time ;
}, 1000);var myComp = mobxReact.observer(React.createClass({
render: function() {
return React.createElement('div', {}, "time is: " this.props.data.time "s");
},
componentWillReact() {
console.log("数据改变,即将更新", this.props.data.time);
}
}));ReactDOM.render(
React.createElement(myComp, {data: myData})
,document.getElementById('ctn1')
);
Provider容器
- Provider 和 inject 等用法,详情见项目文档
- 利用了React的 context 机制,使数据可以向下层传递
<!DOCTYPE html>
<html>
<head>
<script src="https://fb.me/react-15.1.0.js"></script>
<script src="https://fb.me/react-dom-15.1.0.js"></script>
<script src="https://fb.me/react-with-addons-15.1.0.js"></script>
<script src="https://unpkg.com/mobx/lib/mobx.umd.js"></script>
<script src="https://unpkg.com/mobx-react"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="ctn1"></div>
</body>
</html>
代码语言:javascript复制const {inject, observer, Provider} = mobxReact;var Button = inject("color")(observer(class Button extends React.Component {
render() {
return (
<button style={{background: this.props.color}}>
{this.props.children}
</button>
);
}
}))class Message extends React.Component {
render() {
return (
<div>
{this.props.text} <Button>Delete</Button>
</div>
);
}
}class MessageList extends React.Component {
render() {
const children = this.props.messages.map((message, idx) =>
<Message key={idx} text={message.text} />
);
return <Provider color="#ee6699">
<div>
{children}
</div>
</Provider>;
}
}var msgs = [
{text: 111},
{text: 22},
{text: 3333},
{text: 'abc'}
];ReactDOM.render(<MessageList messages={msgs} />, document.getElementById('ctn1'));
* 原创文章转载请注明出处