状态管理
MootingAPP 的状态管理方案说明。
架构概述
应用使用 React Context 进行全局状态管理:
┌─────────────────────────────────────────┐
│ AppProvider │
│ ┌─────────────────────────────────┐ │
│ │ AppContext │ │
│ │ • isConnected │ │
│ │ • isRecording │ │
│ │ • isPaused │ │
│ │ • deviceInfo │ │
│ └─────────────────────────────────┘ │
│ │ │
│ ┌────────────┼────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ Screen A Screen B Screen C │
└─────────────────────────────────────────┘AppContext 实现
jsx
// context/AppContext.jsx
import { createContext, useContext, useState } from 'react';
const AppContext = createContext();
export const AppProvider = ({ children }) => {
// 设备连接状态
const [isConnected, setIsConnected] = useState(false);
// 录音状态
const [isRecording, setIsRecording] = useState(false);
// 暂停状态
const [isPaused, setIsPaused] = useState(false);
// 设备信息
const [deviceInfo, setDeviceInfo] = useState(null);
// 连接设备
const connectDevice = (device) => {
setDeviceInfo(device);
setIsConnected(true);
};
// 断开设备
const disconnectDevice = () => {
setDeviceInfo(null);
setIsConnected(false);
};
return (
<AppContext.Provider
value={{
isConnected,
setIsConnected,
isRecording,
setIsRecording,
isPaused,
setIsPaused,
deviceInfo,
connectDevice,
disconnectDevice,
}}
>
{children}
</AppContext.Provider>
);
};
// Hook
export const useAppContext = () => {
const context = useContext(AppContext);
if (!context) {
throw new Error('useAppContext must be used within AppProvider');
}
return context;
};使用方式
在组件中使用
jsx
import { useAppContext } from '../context/AppContext';
const HomeScreen = () => {
const { isConnected, deviceInfo, isRecording } = useAppContext();
return (
<View>
<Text>
{isConnected ? `已连接: ${deviceInfo.name}` : '未连接设备'}
</Text>
{isRecording && <Text>录音中...</Text>}
</View>
);
};修改状态
jsx
const RecordingScreen = () => {
const { setIsRecording, setIsPaused } = useAppContext();
const startRecording = () => {
setIsRecording(true);
setIsPaused(false);
};
const pauseRecording = () => {
setIsPaused(true);
};
const stopRecording = () => {
setIsRecording(false);
setIsPaused(false);
};
return (
<View>
<Button title="开始" onPress={startRecording} />
<Button title="暂停" onPress={pauseRecording} />
<Button title="停止" onPress={stopRecording} />
</View>
);
};本地状态
页面级别的状态使用 useState:
jsx
const SettingsScreen = () => {
// 本地状态
const [fontSize, setFontSize] = useState(16);
const [language, setLanguage] = useState('zh-CN');
const [isModalVisible, setModalVisible] = useState(false);
return (
<View>
<Slider value={fontSize} onValueChange={setFontSize} />
<Modal visible={isModalVisible}>
{/* ... */}
</Modal>
</View>
);
};状态分类
| 状态类型 | 存储位置 | 示例 |
|---|---|---|
| 全局状态 | AppContext | 设备连接、录音状态 |
| 页面状态 | useState | 表单输入、弹窗显示 |
| 服务器状态 | API 请求 | 用户信息、转写记录 |
未来优化
当前方案适合中小型应用,未来可考虑:
- Redux - 复杂状态管理
- React Query - 服务器状态缓存
- Zustand - 轻量级状态库
- AsyncStorage - 本地持久化