简体   繁体   English

state 未在 React Native 中为新用户更新

[英]state is not getting updated for a new user in react native

My app has a test sheet, if a user passes the test he is shown a passing screen and then the state is saved using asyncstorage.我的应用程序有一个测试表,如果用户通过测试,他会看到一个通过的屏幕,然后使用异步存储保存 state。 But the problem here is, let's say i have user A and user B and user A is currently logged in, he passed the test and the app shows him passing screen and the state is saved.但这里的问题是,假设我有用户 A 和用户 B,用户 A 当前已登录,他通过了测试,应用程序显示他通过了屏幕,state 已保存。 Now user A logs out and user B logs in, he is a completely new user he has never given test before but my app has still saved the state for the user A and keeps showing passing screen even to the user B rather it should not.Can someone help me with this issue?现在用户 A 注销,用户 B 登录,他是一个全新的用户,他以前从未进行过测试,但我的应用程序仍然为用户 A 保存了 state,并且甚至向用户 B 显示通过屏幕,而不是它不应该。有人可以帮我解决这个问题吗?

code:代码:

import React ,{useState, useEffect} from "react";
import {View, Alert, Image, StyleSheet, Text, Modal, TouchableOpacity, TouchableHighlight} from 'react-native';
import Voice from 'react-native-voice';
import auth from '@react-native-firebase/auth';


import AsyncStorage from '@react-native-async-storage/async-storage';
  const key = auth().currentUser.uid + "hasPassed"
  

export const hasPassed = async () => {
    return AsyncStorage.getItem(key).then(result => result != null ? JSON.parse(result) : undefined).catch(e => console.log(e))    
}

export const setHasPassed = async (newPassed) => {
    return AsyncStorage.setItem(key, JSON.stringify({hasPassed: newPassed})).catch(e => console.log(e))
}



export default alpht =({navigation}) => { 

 
 function Check() {
  if (results.includes(words[index])){
 
    Alert.alert('Correct!','You are learning so well!');
    
     if(index==7) {
      if(count<=5)
      {
           
        setHasPassed(true).then(() => setshowpass(true))
        //  setshowpass(true);
      }
      else{
        console.log(count)
        Alert.alert('fail','fail');
      }
    }
    if (index==7){
      setndis(true);
      setdis(true);
      setidis(true);
    }
    else{
   setndis(false);
   setdis(true);
   setidis(true);
    }
   
  }
  else{
    Alert.alert('Ops!','Looks like you went wrong somewhere. Try again!');
    setcount(count+1);
    
    setdis(true);
    setndis(true);
   
    if(count==5){
      Alert.alert('Restest', 'Looks like you had way too many mistakes!')
      setind(0);
      setcount(0);
      setdis(true);
    }
  }
}


  const words=['ceket', 'çilek', 'elma', 'fare', 'öğretmen', 'otobüs', 'şemsiye', 'uçak'];
  const [show, setshow]=useState('');
    const [showpass, setshowpass]=useState(false);
    useEffect(() => {
     //console.log(auth().currentUser.uid);
        setshow(true);
      }, []);

      useEffect(() => {
        const getState = async () => {
          const result = await hasPassed()
          setshowpass(result ? result.hasPassed : false)
      }
      getState()
     
      }, []);

     
      console.log(auth().currentUser.uid)
      if (showpass === false) {

         
        // setshow(true)
        console.log('hey');
       return null
      }
return (
//... other code
)
}

my user logs out using auth().signOut() by the way, It would be great if this issue gets solved i am dealing with it for the past 4,5 days now!顺便说一下,我的用户使用 auth().signOut() 注销,如果这个问题得到解决就太好了我在过去的 4.5 天里一直在处理它!

I don't know exactly what's going wrong in your code, but I believe that the piece of code in your useEffect is fetching the state of user A no matter who is logged in ( state persistence).我不知道您的代码到底出了什么问题,但我相信您的 useEffect 中的这段代码正在获取用户 A 的 state,无论谁登录( state 持久性)。 try testing with user C. check out firebase state persistence in their official documentation.尝试使用用户 C 进行测试。在其官方文档中查看 firebase state 持久性。 I hope I gave you some hints to solve this issue.我希望我给了你一些提示来解决这个问题。

I think this is the problem:我认为这是问题所在:

const key = auth().currentUser.uid + "hasPassed"
  
export const hasPassed = async () => {
    return AsyncStorage.getItem(key).then(result => result != null ? JSON.parse(result) : undefined).catch(e => console.log(e))    
}

export const setHasPassed = async (newPassed) => {
    return AsyncStorage.setItem(key, JSON.stringify({hasPassed: newPassed})).catch(e => console.log(e))
}

key is defined at the top level, outside of the react lifecycle, and thus is subject to having stale values. key是在反应生命周期之外的顶层定义的,因此可能具有陈旧的值。 auth().currentUser may change, the value of key will not (I think). auth().currentUser可能会改变, key的值不会(我认为)。 Instead of storing key as a string, try storing it as a function:不要将密钥存储为字符串,而是尝试将其存储为 function:

// every time getKey is called it will get a fresh instance of currentUser
const getKey = ()=>auth().currentUser.uid + "hasPassed"

export const hasPassed = async () => {
  return AsyncStorage.getItem(getKey()).
    then(result => result != null ? JSON.parse(result) : undefined).
    catch(e => console.log(e))    
}

export const setHasPassed = async (newPassed) => {
  return AsyncStorage.setItem(
    getKey(),
    JSON.stringify({hasPassed: newPassed})
  ).catch(e => console.log(e))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM