mobx6+使用案例
2021-07-08 本文已影响0人
天渺工作室
PS:mobx6版本以后官方不建议使用@observable装饰器了 可看官方案例 https://mobx.js.org/the-gist-of-mobx.html
脚手架 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
import { observable, action, computed, makeObservable} from "mobx";
export class AuthStore {
name = 'kangkang000';
sex = '男';
userObj = {
name: 'kangkang000',
age: 23,
token: '12345689'
}
constructor() {
// mobx6 和以前版本这是最大的区别
makeObservable(this, {
name: observable,
sex: observable,
userObj: observable,
setName: action,
titleName: computed
});
}
setName(v) {
console.log('触发action');
this.name = v;
}
setUserObj(obj) {
this.userObj = obj;
}
get titleName(){
return this.name+'___111';
}
get userObject() {
return this.userObj;
}
}

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;
