1.安装依赖
# 安装 MobX 核心包和 React 绑定
npm install mobx mobx-react-lite
# 如果使用装饰器语法(可选)
npm install --save-dev @babel/plugin-proposal-decorators
2.配置 Babel(如果使用装饰器):
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
// 启用装饰器语法
['@babel/plugin-proposal-decorators', { legacy: true }]
]
};
3.创建 Store:
import { makeAutoObservable, runInAction } from 'mobx';
class CounterStore {
// 定义可观察状态
count = 0;
loading = false;
constructor() {
// 使所有属性和方法可观察
makeAutoObservable(this);
}
// action:修改状态的方法
increment = () => {
this.count += 1;
};
// action:减少计数
decrement = () => {
this.count -= 1;
};
// 异步 action
async fetchInitialCount() {
this.loading = true;
try {
const response = await fetch('https://api.example.com/count');
const data = await response.json();
// 在异步操作中修改状态需要使用 runInAction
runInAction(() => {
this.count = data.count;
this.loading = false;
});
} catch (error) {
runInAction(() => {
this.loading = false;
});
}
}
// computed:计算属性
get doubleCount() {
return this.count * 2;
}
}
// 创建并导出 store 实例
export const counterStore = new CounterStore();
4.创建 Root Store(可选,用于管理多个 store):
import { counterStore } from './counterStore';
import { userStore } from './userStore';
class RootStore {
counterStore;
userStore;
constructor() {
this.counterStore = counterStore;
this.userStore = userStore;
}
}
export const rootStore = new RootStore();
5.创建 Store Context:
import { createContext, useContext } from 'react';
import { rootStore } from './rootStore';
// 创建 Context
export const StoreContext = createContext(rootStore);
// 创建 Hook 用于获取 store
export const useStore = () => {
const store = useContext(StoreContext);
if (!store) {
throw new Error('useStore must be used within StoreProvider');
}
return store;
};
6.配置 Provider:
import { StoreContext } from './stores/StoreContext';
import { rootStore } from './stores/rootStore';
const App = () => {
return (
<StoreContext.Provider value={rootStore}>
<NavigationContainer>
{/* 你的应用组件 */}
</NavigationContainer>
</StoreContext.Provider>
);
};
7.在组件中使用:
import { observer } from 'mobx-react-lite';
import { useStore } from '../stores/StoreContext';
// observer 使组件响应 store 的变化
export const Counter = observer(() => {
// 获取 store
const { counterStore } = useStore();
return (
<View>
{/* 显示加载状态 */}
{counterStore.loading ? (
<ActivityIndicator />
) : (
<>
{/* 显示计数 */}
<Text>Count: {counterStore.count}</Text>
{/* 显示双倍计数 */}
<Text>Double Count: {counterStore.doubleCount}</Text>
{/* 按钮操作 */}
<Button
title="+"
onPress={counterStore.increment}
/>
<Button
title="-"
onPress={counterStore.decrement}
/>
{/* 异步操作 */}
<Button
title="Fetch Count"
onPress={() => counterStore.fetchInitialCount()}
/>
</>
)}
</View>
);
});
8. MobX 的关键概念:
- observable:可观察的状态
- action:修改状态的方法
- runInAction:在异步操作中安全地修改状态