react、react-native 配置 Mobx,Mobx的多 store
安装 Mobx
及所需相关 babel
依赖
Mobx
npm insatall mobx --save npm insatall mobx-react --save
babel
npm install babel-plugin-transform-decorators-legacy --save-dev npm install @babel/plugin-proposal-decorators --save-dev # 或者 npm install @babel/plugin-proposal-decorators babel-plugin-transform-decorators-legacy --save-dev
配置 babel
.babelrc
或者 babel.config.js
或者在 package.json
中
plugins:[
["@babel/plugin-proposal-decorators", {"legacy":true}],
["@babel/plugin-proposal-class-properties", {"loose":true}]
]
- 配置 mobx,多 store 组合
文件结构
project
│ app.js
└───src
│ │
│ └───stores
│ │ todo.js
│ │ index.js
│ │ ...
│ └───pages
│ │ todoPage.js
│ │ ...
│
4.1 src/stores/todo.js
import {
observable,
action,
computed,
} from 'mobx';
export class TodoStore {
@observable name = '555';
// 不接受任何参
@computed get getName() {
return this.name;
}
// @autorun( () => {
// })
@action.bound setName(name) {
console.log(this.name, name);
}
// 或者
@action
setName = (name) => {
console.log(this.name, name);
}
}
export const STORE_TODO = 'todoStore';
export default TodoStore;
4.2 src/stores/index.js
import TodoStore, { STORE_TODO, TodoType } from "./todo";
class RootStore {
[STORE_TODO]: TodoType
constructor() {
this[STORE_TODO] = new TodoStore();
}
}
export default new RootStore();
4.4 /app.js
+ import RootStore from './src/store/index';
+ import { Provider } from 'mobx-react';
const App: () => React$Node = () => {
return (
+ <Provider {...RootStore}>
.....
+ </Provider>
);
};
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 kshao-blog-前端知识记录!
评论