You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native+Django应用实现用户持久登录(关机后仍保持)

React Native 实现关闭应用后保持登录状态

要解决关闭应用(甚至关机)后仍保持登录状态的问题,核心是把登录状态持久化存储到设备本地,下面是具体实现步骤和代码修改:

一、选合适的持久化存储方案

  • 如果你用Expo开发,优先用expo-secure-store,它会加密存储数据,适合存登录凭证(用户名、后端返回的token等敏感信息),比普通存储更安全。
  • 纯React Native项目可以用@react-native-async-storage/async-storage,但敏感数据建议额外加密处理。

二、安装依赖(以Expo为例)

npx expo install expo-secure-store

三、修改登录逻辑,存储登录状态

在你的login.js里,登录成功后把用户信息存到本地存储:

  1. 先导入存储库:
import * as SecureStore from 'expo-secure-store';
  1. 把log函数改成异步函数,登录成功后存储用户名:
const log = async () => {
  fetch(`http://192.168.5.223:8000/home/login/`, {
    method: 'POST',
    headers: {
        "Content-Type": 'application/json'
       },
    body: JSON.stringify({ username: username, password: password}),
  })
  .then( res => res.json())
  .then( async res => {
    console.log(res)
    
    if (res.valid === true){
      // 把用户名存到本地加密存储
      await SecureStore.setItemAsync('loggedInUser', username);
      
      if (res.set === true){
        props.navigation.navigate("Home", {"user": username})
      } else {
        props.navigation.navigate("Profile", {"user": username})
      }
      
    } else {
      props.navigation.navigate("Login", {'message': "username/password are incorrect"})
    }
  })
  .catch( error => console.log(error))
}

四、应用启动时自动检查登录状态

在你的入口组件(比如App.js)里,启动时读取本地存储的登录信息,自动跳转到对应页面:

import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import Login from './login';
import Home from './Home';
import Profile from './Profile';
import Signup from './Signup';
import * as SecureStore from 'expo-secure-store';

const Stack = createStackNavigator();

export default function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    checkLoginStatus();
  }, []);

  const checkLoginStatus = async () => {
    // 读取本地存储的用户信息
    const storedUser = await SecureStore.getItemAsync('loggedInUser');
    if (storedUser) {
      setIsLoggedIn(true);
      setUser(storedUser);
    }
    setLoading(false);
  };

  // 加载状态显示
  if (loading) {
    return (
      <View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
        <Text>加载中...</Text>
      </View>
    );
  }

  return (
    <NavigationContainer>
      <Stack.Navigator>
        {isLoggedIn ? (
          // 根据登录时的set状态,也可以把res.set的值一起存起来,这里简化处理
          <>
            <Stack.Screen name="Home" component={Home} initialParams={{user}} />
            <Stack.Screen name="Profile" component={Profile} initialParams={{user}} />
          </>
        ) : (
          <Stack.Screen name="Login" component={Login} />
        )}
        <Stack.Screen name="Signup" component={Signup} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

五、登出功能(可选)

如果需要登出,在主页或个人中心添加登出按钮,清除本地存储并跳转登录页:

const logout = async () => {
  await SecureStore.deleteItemAsync('loggedInUser');
  props.navigation.navigate("Login");
};

注意事项

  • 绝对不要存储明文密码,只存登录后的有效凭证(用户名、JWT token等)。
  • 如果用JWT,建议同时存储token的过期时间,启动时检查是否过期,过期则自动清除登录状态。
  • 纯React Native项目用AsyncStorage的话,导入方式是import AsyncStorage from '@react-native-async-storage/async-storage',API和SecureStore一致(setItemAsync、getItemAsync、deleteItemAsync)。

内容的提问来源于stack exchange,提问作者Itay Lador

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 21:18:37