状态管理 Mbox
安装
bash
npm i mobx-react # 支持函数组件和类组件
npm i mobx-react-lite # 仅支持函数组件
使用
提取模块
在store
文件夹下创建user.js
文件,用于提取模块
js
import { makeAutoObservable } from "mobx";
class User {
// 构造函数
constructor() {
makeAutoObservable(this, {}, { autoBind: true });
}
// 成员属性
username = "张三";
age = 18;
// 计算属性
get bornYear() {
return new Date().getFullYear() - this.age;
}
// 成员方法
changeName(newName) {
this.username = newName;
}
// 年龄 +
increment(content) {
this.age += content;
}
// 年龄 -
decrement(content) {
this.age -= content;
}
}
export default User;
模块整合
- 新建
store\index.jsx
文件,用于整合模块,特别注意是index.jsx
文件,不是index.js
文件
ts
import { createContext, useContext } from "react";
import User from "./User";
// 合并
class RootStore {
constructor() {
this.user = new User();
}
}
// 传递的值
const rootStore = new RootStore();
// 创建上下文
const RootStoreContext = createContext(rootStore);
// 包裹层
const RootStoreProvider = ({ children }) => {
return (
<RootStoreContext.Provider value={rootStore}>
{children}
</RootStoreContext.Provider>
);
};
export default RootStoreProvider;
// 自定义hook方便传递数据
export const useRootStore = () => {
return useContext(RootStoreContext);
};
改变入口文件中的代码
main.jsx
文件
js
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";
import RootStoreProvider from "./store/index.jsx";
createRoot(document.getElementById("root")).render(
<RootStoreProvider>
<App />
</RootStoreProvider>
);
组件中使用公共数据
包裹函数
使用 hook 调用
js
// 包裹层
import { observer } from "mobx-react";
import { useRootStore } from "./store";
function Son() {
const { user } = useRootStore();
const { username, age, changeName, increment, decrement } = user;
return (
<div>
<h1>
姓名{username}---年龄{age}
</h1>
<button onClick={() => changeName("李四")}>点击改变姓名</button>
<button onClick={() => increment(3)}>点击增加3年年龄</button>
<button onClick={() => decrement(2)}>点击减少2年年龄</button>
</div>
);
}
export default observer(Son);
引用 Son 这个组件
js
import React from "react";
import Son from "./Son";
function App() {
return (
<div>
<Son />
</div>
);
}
export default App;