mobx
-
observer观测器: 带有观测器的react组件或者属性被mobx实时观测
-
observable可观测对象: 有mobx 建立的可观测对象
-
action 更新事件:标识观测对象的改变事件
Actions:一般可以改变观测变量状态的代码,类似于setState,严格模式下,只有在动作中才可以修改状态
mobx 4个函数
-
state 状态 相当于数据的存放库
-
Derivations : 驱动
-
Computed value : 计算值 两个及以上状太生成一个新值
-
reactions: 反应
安装包 npm install mobx mobx-react --save
创建store 实例class
import { configure, observable, action } from 'mobx'
import IRootStore from './modules/IRootStore'
import UserOptions from './modules/user'
class InteStore implements IRootStore {
constructor(){
this.initStore()
}
@observable
UserStore!: UserOptions
@action('初始化store')
initStore = () => {
this.UserStore = new UserOptions()
}
}
export function StoreConfig() {
return new InteStore();
}
创建userStore
import { action, computed, makeObservable, observable, runInAction } from "mobx";
import { UserInterFace } from './InterfaceStore/userInterface'
/**
* 对应的PC端仪表盘数据
*/
class User {
/**
* id
*/
@observable
id: number | undefined;
/**
* name
*/
@observable
userInfo!: UserInterFace
constructor() {
makeObservable(this)
}
@action
setUserInfo(userInfo: UserInterFace) {
this.userInfo = userInfo
}
@action.bound
setId(id: number | undefined) {
this.id = id
}
}
export default User;
全局注入store
import { Provider } from 'mobx-react';
import App from './App';
import { StoreConfig } from '../src/stores/index'
import ReactDOM from 'react-dom/client';
import Vconsole from 'vconsole'
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
let store = StoreConfig();
root.render(
<Provider {...store}>
<App />
</Provider>
);
函数使用mobx示例
import React, { useEffect, Suspense } from "react";
import { Outlet } from "react-router-dom";
import { observer, inject } from "mobx-react";
import IRootStore from "../stores/modules/IRootStore";
import { Icon } from '@nutui/nutui-react';
import { useSearchParams } from "react-router-dom";
import { queryLoginUser } from '../api/beefiles'
const Home = inject('UserStore')(observer((props: IRootStore) => {
// inject('UserStore') 注入user store 信息
const { UserStore } = props // 获取UserStore 数据
const [searchParams] = useSearchParams();
let token: string | null = searchParams.get("token");
if (token) {
sessionStorage.setItem("token", token);
}
useEffect(() => {
const data = {}
queryLoginUser(data).then((res) => {
if (res && (res as any).code === 200) {}
UserStore?.setUserInfo(res.data) // 使用store 方法 设置store user数据
})
}, [])
return (
<Suspense
fallback={
<div
style={{
width: "100vw",
height: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
flexDirection: "column",
}}
>
<Icon name="loading"></Icon>
</div>
}
>
<div className="App app-box" id="App">
{/* 有嵌套路由的场景需要使用 */}
<Outlet></Outlet>
</div>
</Suspense>
);
}));
export default Home;