1. 安装mobx相关工具
yarn add mobx mobx-react-lite
2.1 若不进行统一管理,直接使用mbox(后面会说统一管理)
新建一个store.js文件夹,下面新建一个count.js文件
import { makeAutoObservable } from "mobx";
class Counter{
count = 0
constructor() {
makeAutoObservable(this)
}
addCount = () => {
this.count++
}
}
const counter = new Counter()
export { counter }
2.2 在相应的模块引入
import React from 'react'
import { counter } from '@/store/count.js'
引入observer
import { observer } from 'mobx-react-lite';
function Box() {
console.log(counter.count);
return (
<div>
{counter.count}
<button onClick={counter.addCount}>
加
</button>
</div>
)
}
export default observer(Box)
3.1 使用mbox进行computed计算
import { makeAutoObservable } from "mobx";
class Counter{
list = [1,2,3,4]
constructor() {
makeAutoObservable(this)
}
get filterList() {
return this.list.filter(item =>item>2)
}
addList = () => {
this.list.push(5)
}
}
const counter = new Counter()
export { counter }
3.2引入
import React from 'react'
import { counter } from '@/store/count.js'
import { observer } from 'mobx-react-lite';
function Box() {
return (
<div>
{counter.filterList}
<button onClick={counter.addList}>push</button>
</div>
)
}
export default observer(Box)
4.统一管理mbox
如果要统一管理的话,和直接使用有一些差别,(不能在里面直接实例化,否则会报错,因为你会在统一管理里面实例化)
1.新建一个store文件夹
2.新建index.js统一管理
3.其他的文件随意命名,不过一般xxx.Store.js的命名方式
话不多说,直接上代码
这里是login.Store.js文件
import { makeAutoObservable } from "mobx";
import { http, storeToken, getToken,removeToken } from "../API";
class Login{
token = getToken() || ''
constructor() {
makeAutoObservable(this)
}
toLogin = async ({mobile,code}) => {
const {data:res} = await http.post('/authorizations',{
mobile,code
})
this.token = res.token
storeToken(this.token)
}
loginOut = () => {
this.token = ''
removeToken()
}
}
export default Login
import React, { useContext } from "react";
import Login from "./login.Store";
class RootStore {
constructor() {
this.login = new Login()
}
}
const rootStore = new RootStore()
const context = React.createContext(rootStore)
const useStore = () => useContext(context)
export {useStore}
在函数组件引入并使用
import { useStore } from '@/store'
import { useNavigate } from 'react-router-dom'
const { login } = useStore()
const navigate = useNavigate()
const onFinish = async (values) => {
await login.setToken({
mobile: values.mobile,
code: values.code
})
navigate('/layout/home', { replace: true })
message.success('登录成功');
};
|