本教程总共5篇,每日更新一篇,请关注我们!你可以进入历史消息查看以往文章,也敬请期待我们的新文章!
1、React第三方组件6(状态管理之Mobx的使用①简单使用)---2018.03.28
2、React第三方组件6(状态管理之Mobx的使用②TodoList上)---2018.03.29
3、React第三方组件6(状态管理之Mobx的使用③TodoList中)---2018.03.30
4、React第三方组件6(状态管理之Mobx的使用④TodoList下)---2018.04.02
5、React第三方组件6(状态管理之Mobx的使用⑤异步操作)---2018.04.03
开发环境:Windows 8,node v8.9.1,npm 5.5.1,WebStorm 2017.2.2
MobX 一个很有趣的react状态管理工具,在react-native中文网上被着重介绍过!我们今天来用用这个工具,我直接上代码,讲解怎么用,很多概念性的东西,还得大家去查资料,本节不作重点介绍!
1、我们在demo目录下新建一个mobx文件夹,并新建Index.jsx
import React from 'react';
import {HashRouter, Route, NavLink, Redirect} from 'react-router-dom';
import Mobx1 from './mobx1/Index'
const Index = ({match}) =>
className="nav">
to="/Mobx/Mobx1" activeClassName="selected">Mobx1
exact path={`${match.url}`}
render={() => (to={`${match.url}/Mobx1`}/>)}/>
path={`${match.url}/Mobx1`} component={Mobx1}/>
;
export default Index;
2、在mobx目录下新建Index.jsx
import React from 'react';
class Index extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
}
render() {
return (
mobx
);
}
}
export default Index;
3、修改demo目录下的Index.jsx文件
4、安装依赖
npm i -S mobx mobx-react
5、安装 @ 装饰器(已安装可以忽略)
npm i -D babel-plugin-transform-decorators-legacy
修改 .babelrc
{
"presets":["react","env"],
"env":{
"development": {
"presets":["react-hmre"]
}
},
"plugins": ["transform-decorators-legacy","transform-class-properties"]
}
6、新建 State.js
import {observable, action} from 'mobx';
class State {
@observable num = 0;
@action addNum = () => {
this.num++;
};
}
export default State
7、修改Index.jsx , 导入State.js
完整代码
import React from 'react';
import {useStrict} from 'mobx';
import {observer} from 'mobx-react';
import State from './State'
useStrict(true);
const newState = new State();
@observer
class Index extends React.Component {
render() {
return (
{newState.num}
)
}
}
export default Index
8、我们看下浏览器效果
9、修i该下Index.jsx
import React from 'react';
import {useStrict} from 'mobx';
import {observer} from 'mobx-react';
import State from './State'
useStrict(true);
const newState = new State();
@observer
class Index extends React.Component {
render() {
return (
num1: {newState.num1}
num2: {newState.num2}
total:{newState.total}
)
}
}
export default Index
10、修改下 State.js
import {observable, action, computed} from 'mobx';
class State {
@observable num1 = 0;
@observable num2 = 0;
@action addNum1 = () => {
this.num1++;
};
@action addNum2 = () => {
this.num2++;
};
@computed
get total() {
return this.num1 + this.num2;
}
}
export default State
11、看下浏览器效果 total 会被自动计算出来
本文完
禁止擅自转载,如需转载请在公众号中留言联系我们!
感谢童鞋们支持!
如果你有什么问题,可以在下方留言给我们!