React的mobx使用方式

一、创建文件

stores
—– auth.js 例子文件
—– index.js 总入口

二、安装

1
2
yarn add mobx
yarn add mobx-react

三、书写相应代码

auth.js

  1. import相应的文件
1
import { observable, action } from "mobx"
  1. 声明class类,并导出
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class AuthStore {
@observable 变量名 = 值
@boservable values = {
username = "梁又文"
sex = "男"
}

@action 方法名(参数) {
console.log(参数)
}
@action setName(name){
this.values.username = name
}
}

export { AuthSotre }

index.js

  1. import相应文件
1
2
3
import React, { createContext, useContext } from "react"
import { 类名 } from "../stores/文件名"
import { AuthSotre } from "../stores/auth"
  1. 创建Context对象
1
2
3
4
const context = createContext({
定义方法名: new 类名(),
authStore: new AuthStore()
})
  1. 将Context对象全局导出
1
export const useStores = () => useContext(context)

四、配置package.json

  1. 将react隐藏的webpack暴露出来,释放之前请先提交代码
1
yarn eject
  1. 安装插件
1
yarn add @babel/plugin-proposal-decorators
  1. 修改package.json
1
2
3
4
5
6
7
8
"babel": {
"plugins": [
["@babel/plugin-proposal-decorators", {"legacy": true}]
],
"presets": [
"react-app"
]
}

五、在组件中进行使用

  1. import相应文件
1
2
import { observer } from "mobx-react"
import { useStores } from "../stores"
  1. 使用observer监控组件,并解构我们需要的对象出来并使用
1
2
3
4
5
6
7
8
9
const Demo = observer(()=>{
const { AuthStore } = useStores()

return (
<>
<h1>我是Demo组件</>
</>
)
})
  1. 解构后我们就可以使用该对象的属性及方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const Demo = observer(()=>{
const { AuthStore } = useStores()

const changeName = () => {
AuthStore.setName("改名字后的梁又文")
}

return (
<>
<h1>我是Demo组件,我的名字叫{ AuthStore.values.username }</h1>
<button onClick={changeName}>改名字</button>
</>
)
})