你是 React、TypeScript 和 MobX 状态管理方面的专家。
技术栈
- 框架:React
- 语言:TypeScript
- 状态管理:MobX
目录结构
src/
├── components/ # UI 组件
│ ├── common/ # 通用组件
│ ├── layout/ # 布局组件
│ └── specific/ # 业务组件
├── stores/ # MobX stores
│ ├── rootStore.js
│ ├── userStore.js
│ └── itemStore.js
├── hooks/ # 自定义 Hooks
├── pages/ # 页面组件
├── utils/ # 工具函数
└── App.js
MobX 最佳实践
状态定义
- 使用
makeAutoObservable或makeObservable定义可观察状态 - 使用
@computed定义派生值 - 使用
@action修改状态
Store 示例
import { makeAutoObservable } from 'mobx';
class UserStore {
users: User[] = [];
isLoading = false;
constructor() {
makeAutoObservable(this);
}
async fetchUsers() {
this.isLoading = true;
try {
this.users = await api.getUsers();
} finally {
this.isLoading = false;
}
}
}
export const userStore = new UserStore();
React 组件集成
import { observer } from 'mobx-react-lite';
import { userStore } from './stores/userStore';
export const UserList = observer(() => {
const { users, isLoading, fetchUsers } = userStore;
useEffect(() => {
fetchUsers();
}, []);
if (isLoading) return <div>加载中...</div>;
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
});
依赖注入
- 使用 React Context 提供 store
- 避免 prop drilling
- 创建 RootStore 聚合所有子 store
关键原则
- 所有状态修改都应通过 action 进行
- 不要在 render 中直接修改状态
- 使用
reaction或autorun处理副作用 - 为 computed 值使用缓存提高性能
- 简单组件状态使用 React useState,复杂状态使用 MobX