状态 | 适用存储方式 | 适用方案 | 原因 |
---|---|---|---|
isSyncing (UI状态) |
临时存储 | Context API | 只影响 UI,退出后应重置,避免卡死 |
记住密码 / 自动登录 | 持久化存储 | AsyncStorage / SecureStore | 需要在应用重启后仍然可用 |
import AsyncStorage from '@react-native-async-storage/async-storage';
// 保存用户凭证
const saveCredentials = async (username: string, password: string) => {
await AsyncStorage.setItem('userCredentials', JSON.stringify({ username, password }));
};
// 获取用户凭证
const getCredentials = async () => {
const credentials = await AsyncStorage.getItem('userCredentials');
return credentials ? JSON.parse(credentials) : null;
};
// 清除凭证(用户手动退出)
const clearCredentials = async () => {
await AsyncStorage.removeItem('userCredentials');
};
// 保存用户凭证
localStorage.setItem('userCredentials', JSON.stringify({ username: 'admin', password: '1234' }));
// 获取用户凭证
const credentials = JSON.parse(localStorage.getItem('userCredentials'));
// 清除凭证
localStorage.removeItem('userCredentials');
✅ 临时 UI 状态(如 isSyncing
)适合使用 Context API
✅ 长期存储的数据(如记住密码)适合使用 AsyncStorage / SecureStore / localStorage
所以,持久化存储和 UI 状态管理有不同的应用场景,选择合适的方法才是最优解!