PS:mobx6版本以后官方不建议使用@observable装饰器了
文章案例https://www.jianshu.com/p/33812a38ecff
脚手架 create-react-app
一、安装
//npm yarn 随需求,尽量不要混用,混用有些资源可能会出现掉包
yarn add mobx
yarn add mobx-react
// 版本号
"mobx": "^6.3.2",
"mobx-react": "^7.2.0",

二、配置package.json
1.把隐藏的webpack暴露出来,释放之前记得请先提交代码 git commit 一次
yarn run eject

2.安装@babel/plugin-proposal-decorators 插件 必须的
yarn add @babel/plugin-proposal-decorators

3.修改添加 package.json配置 (手动)
"babel": {
"plugins": [
["@babel/plugin-proposal-decorators", {"legacy": true}]
],
"presets": [
"react-app"
]
}

三、定义mobx的store
1.目录机构(mobx支持多个多个状态模块)
stores
----- auth.js 模块1
----- test.js 模块2
----- index.js 总入口

2.模块 auth.js
// auth.js和test.js 一模一样 展示auth.js做案例
// @action.bound 和 @action 区别 https://cn.mobx.js.org/refguide/action.html
import { observable, action, computed, makeObservable } from "mobx";
export class AuthStore {
// 定义变量
@observable name = 'zhangsan000';
@observable sex = '男';
@observable userObj = {
name: 'zhangsan000',
age: 233,
token: '12345689'
}
// 初始化
constructor() {
// mobx6版本以后 必须得在初始化加makeObservable
//也可以按照官方的方法makeObservable 案例,就不用写@observable装饰器了https://mobx.js.org/README.html
makeObservable(this);
}
// 动作
@action.bound
setName(v) {
console.log('触发action');
this.name = v;
}
@action
setUserObj(obj) {
this.userObj = obj;
}
// 计算属性
@computed get titleName(){
return this.name+'___111';
}
}

3.定义导出出口index.js
import { AuthStore } from "./auth";
import { TestStore } from "./test";
export const store = {
authStore: new AuthStore(),
testStore: new TestStore()
};

4.在react 工程入口 导入
import { store } from './store/index';
import { Provider} from 'mobx-react';
ReactDOM.render(
<React.StrictMode>
<Provider store = {store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);

四、在页面中使用mobx,并且通过action 改变mobx
import React, { Component, PureComponent } from "react";
import { observer, inject } from 'mobx-react';
@inject( 'store')
@observer
class Index extends PureComponent {
constructor(props) {
super(props);
console.log(this.props);
this.state = { };
}
render() {
const { authStore, testStore } = this.props.store;
return (
<div>
{authStore.name}/
{testStore.name}/
{authStore.titleName}
<br />
<button onClick = { () => {
authStore.setName(new Date().getTime());
} }>点击按钮触发action</button>
</div>
);
}
}
export default Index;

网友评论