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

React Native+TypeScript切换登录后仍显示原用户信息求助

问题:退出登录后新用户登录,AsyncStorage仍保留原用户信息

开发基于React Native + TypeScript的登录应用时,遇到以下问题:用户退出登录后,新用户登录时AsyncStorage仍会显示原用户的信息,需排查问题。以下是LoginScreen组件代码:

import { StyleSheet, Text, View, Alert, TextInput, TouchableOpacity, Image, Switch } from 'react-native';
import { Controller, useForm } from "react-hook-form"
import AsyncStorage from '@react-native-async-storage/async-storage';
import { router } from 'expo-router';
import { useEffect, useState } from "react";

import * as React from 'react'


export default function LoginScreen() {
  
  const { control, handleSubmit } = useForm({
    defaultValues: {
      email: "",
    },
    
  });

  const [text, setText] = useState('');
  
  const onSubmit = (data) => {
    console.log(data);
    fetch("API", {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data),
    })
      .then((response) => response.json())
      .then(async (response) => {
        if (response.status === "success") {
          await AsyncStorage.setItem('email',JSON.stringify(data));
          router.replace('./home');
        } else {
          setText('Email address not found')
        }
      })
      .catch((error) => console.error(error));
  };


  const [isLoaded, setIsLoaded] = useState(false)
  const [isEnabled, setIsEnabled] = useState(false)
  const switchDefaultColor = "#ff00ff"
  const primaryColor = "#dd00dd"

  const toggleSwitch = async () => {
    const updated = !isEnabled
    await AsyncStorage.setItem('enableBiometric', updated.toString());
    setIsEnabled(updated);
  };

  const printSomething = async () => {
    try {
      const value = await AsyncStorage.getItem('enableBiometric');
      console.log(value);
    } catch (err) {
      console.log(err);
    }
  };

  React.useEffect(() => {
     AsyncStorage.getItem('enableBiometric').then((value) => {
       const enableBiometric = value === "true" ? true : false
       setIsEnabled(enableBiometric)
       setIsLoaded(true);
     });
  }, [])

  if(isLoaded === false ) {
    return null
  }

  {isEnabled ? 
    router.replace('./fingerprint') : 
     router.replace('./login')}
 

  return (
    <>
<View style={styles.main}>
       <View style={{ width: "100%", position: "absolute", top: 20,   justifyContent: 'center', 
  alignItems: 'center', }}>
      <Image
      source={require('@/assets/images/shield.png')}
        resizeMode="contain"
        style={styles.reactLogo} />

<Text style={styles.headingtext}>Log in to audiesafe</Text>
</View>
  
<View style={{ width: "85%", position: "absolute", top: 300 }}>

<Text style={{marginLeft: 6, fontSize: 16, color: "red", marginBottom: 4}}>
{text}
      </Text>
        <Controller
          control={control}
          name={"email"}
          render={({ field: { value, onChange, onBlur } }) => (
            <TextInput
              placeholder="Enter email address"
              style={styles.input}
              value={value}
              onChangeText={onChange}
              onBlur={onBlur}
              placeholderTextColor="lightgrey" />
          )} />


        
      <TouchableOpacity onPress={handleSubmit(onSubmit)} style={styles.button}>
        <Text style={{ color: '#fff', textAlign: "center", fontWeight: 500, fontSize: 16 }}>Continue</Text>
      </TouchableOpacity>
      </View>
        </View>
     </>
  )
}

问题原因及解决方案

核心原因

退出登录流程中缺少清除AsyncStorage用户数据的逻辑,导致旧用户信息残留。

解决步骤

  1. 添加退出登录时的清除逻辑
    在退出登录的按钮/处理函数中,必须主动清除存储的用户信息:

    const handleLogout = async () => {
      // 清除指定的用户邮箱数据
      await AsyncStorage.removeItem('email');
      // 若还有其他用户相关数据(如token),需同步清除
      // await AsyncStorage.removeItem('userToken');
      // 跳回登录页
      router.replace('./login');
    };
    

    若需要清除所有应用存储数据(包含生物识别设置等),可使用await AsyncStorage.clear(),根据业务需求选择。

  2. 优化登录时的数据覆盖逻辑
    当前登录代码的setItem会覆盖旧值,但如果退出时未清除,新用户登录前存储仍会保留旧数据。可在登录请求前先清除旧数据,避免极端情况:

    const onSubmit = (data) => {
      console.log(data);
      // 先清除旧数据
      AsyncStorage.removeItem('email')
        .then(() => fetch("API", {
          method: "POST",
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data),
        }))
        .then((response) => response.json())
        .then(async (response) => {
          if (response.status === "success") {
            await AsyncStorage.setItem('email', JSON.stringify(data));
            router.replace('./home');
          } else {
            setText('Email address not found')
          }
        })
        .catch((error) => console.error(error));
    };
    
  3. 修复路由跳转逻辑
    当前组件内直接执行的路由跳转代码会在每次渲染时触发,可能干扰登录页正常渲染,建议移至useEffect中:

    useEffect(() => {
      if (isLoaded && isEnabled) {
        router.replace('./fingerprint');
      }
    }, [isLoaded, isEnabled]);
    

额外排查点

  • 确认退出登录时确实调用了清除AsyncStorage的函数,未被逻辑分支跳过。
  • 可在登录前和退出后打印存储的邮箱值,验证数据是否被正确清除:
    const checkStoredEmail = async () => {
      const storedEmail = await AsyncStorage.getItem('email');
      console.log('当前存储的邮箱:', storedEmail);
    };
    

内容的提问来源于stack exchange,提问作者Stuart Cornes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 01:12:32