React mobx

React mobx

一月 25, 2021

mobx 库

安装

  1. 创建项目
1
2
$ create-react-app app
$ cd app
  1. 配置文件抽离
1
$ yarn eject
  1. 安装 mobx mobx-react
1
$ yarn add mobx mobx-react
  1. 配置装饰器(修饰器 es6) babel
1
2
3
4
$ yarn add babel-plugin-transform-decorators-legacy -D
$ yarn add @babel/preset-env -D
$ yarn add babel-plugin-transform-class-properties -D
$ yarn add @babel/plugin-proposal-decorators -D
  1. 配置 package.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"babel": {
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
"transform-class-properties"
],
"presets": [
"react-app",
"@babel/preset-env"
]
},

基本用法步骤

  1. 新建 store —- src/store/index.js
1
2
3
4
5
6
7
8
// 打造store
import homeStore from "./homeStore";

const store = {
homeStore,
};

export default store;
  1. src/index.js 入口文件做跨组件通信
1
2
3
4
5
6
7
8
9
10
import store from "./store";
import { Provider } from "mobx-react";

// ...
// App用Provider包裹起来 并绑定store跨组件通信
<Provider store={store}>
<App />
</Provider>;

// ...
  1. src/store/homeStore.js 中打造 homeStore 数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// home数据
import { action, observable, computed, makeAutoObservable } from "mobx";

class Home {
// mobx6要求数据修改必须通过构造函数的makeAutoObservable
constructor() {
makeAutoObservable(this);
}
// observable 定义state
@observable count = 0;
// action 定义方法
@action setCount = () => {
this.count++;
};
// computed 定义计算属性
@computed get newCount() {
return this.count * 10;
}
}

const homeStore = new Home();

export default homeStore;

在类组件中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import React, { Component } from "react";
import { inject, observer } from "mobx-react";

@inject("store")
@observer
class Home extends Component {
render() {
const {
store: {
homeStore: { count, setCount, newCount },
},
} = this.props;
return (
<div>
<button onClick={setCount}> + </button>
<p> {count} </p>
<p> {newCount} </p>
</div>
);
}
}
export default Home;

在函数组件中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import React from "react";
import { useLocalStore, Observer, useObserver } from "mobx-react";
import store from "../store";
export default function Home() {
const localStore = useLocalStore(() => store);
const { homeStore } = localStore;
// Observer组件来实现更新
// return (
// <Observer>
// {() => (
// <div>
// <button onClick={homeStore.setCount}>+</button>
// <p>{homeStore.count}</p>
// </div>
// )}
// </Observer>
// );

// useObserver hook 来更新

return useObserver(() => (
<div>
<button onClick={homeStore.setCount}>+</button>
<p>{homeStore.count}</p>
</div>
));
}