Mobx6 + React + Typescript 实践
MobX 是一个React状态管理方案,它通过运用透明的函数式响应编程(Transparent Functional Reactive Programming,TFRP)使状态管理变得简单和可扩展。
使用 create-react-app
来快速创建 react 与 typescript 的环境。
需要安装依赖如下:
- mobx
- mobx-react 或 mobx-react-lite
pnpm install mobx mobx-react-lite
第一步,创建 store 目录。
src 目录下新建 store 文件夹,并创建 globalStore.ts 文件。
globalStore.ts
import {makeAutoObservable, observable, action, runInAction} from 'mobx'
// 定义用户信息数据store接口
export interface IData {
name: string // 昵称
age: number // 年龄
info: string // 自我介绍
editName: (str: string) => void;
}
class GlogalStore {
name = '嘻嘻'
age = 18
info = '请多指教'
constructor() {
// 方式一: 自动转化 target 对象的属性和方法
makeAutoObservable(this)
// 方式二: 手动注解
makeObservable(this, {
name: observable,
age: observable,
info: observable,
editName: action,
})
}
editName(name: string) {
runInAction(() => {
this.name = name
})
}
}
export default new GlogalStore()
第二步,创建 index 页面。
src 目录下新建 pages/Index/index.tsx 文件。
index.tsx
import {observer} from 'mobx-react-lite'
import globalStore from 'src/store/globalStore'
const Index = (props: any) => {
return (
<>
<div>
昵称:<span>{globalStore.name}</span>
年龄:<span>{globalStore.age}</span>
自我介绍:<span>{globalStore.info}</span>
修改:<input type="text" @blur={(e) => globalStore.setName(e.target.value)} />
</div>
</>
)
}
export default observer(Index)