为什么“记住密码”适合持久化?

发布于:2025-02-10 ⋅ 阅读:(64) ⋅ 点赞:(0)

特性 1:应用重启后仍需生效

  • 记住密码的本质是长期存储用户的登录凭证(如用户名、密码、JWT Token),即使用户关闭应用、重启设备,仍然可以自动登录。
  • 持久化存储方案
    • React Native 推荐使用 AsyncStorageSecureStore(Expo)
    • Web 端可以用 localStorage / IndexedDB / Cookies

特性 2:不受组件生命周期影响

  • 记住密码的逻辑应该独立于 UI 组件,即使应用进入后台、前台,状态都应该保持一致。
  • 因此,Context API 不是最佳方案,因为它的状态会在应用退出时被清空,而持久化存储可以确保数据长期可用。

对比:“记住密码” vs. “isSyncing”

状态 适用存储方式 适用方案 原因
isSyncing (UI状态) 临时存储 Context API 只影响 UI,退出后应重置,避免卡死
记住密码 / 自动登录 持久化存储 AsyncStorage / SecureStore 需要在应用重启后仍然可用

记住密码的最佳实现方式

🔹 React Native - 使用 AsyncStorage

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');
};

🔹 Web - 使用 localStorage

// 保存用户凭证
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 状态管理有不同的应用场景,选择合适的方法才是最优解! 🚀


网站公告

今日签到

点亮在社区的每一天
去签到