AsyncStorage 不存储数据,随后不检索数据

AsyncStorage not storing data and subsequently does not retrieve data

我正在使用 expo 和 react-native 我正在尝试使用 AsyncStorage 在持久存储中保存 3 个值 这样我就可以从应用程序的任何地方获取它, 但是 asyncstorage 没有保存或检索,

我已经多次重写代码和几种不同的方法,并尝试了一些教程,但没有任何效果,

所以这是我保存数据的页面代码 (Login.js)

import React, { useState} from 'react'
import { View, Text,TextInput ,Button,SafeAreaView,Image,} from 'react-native'

import { ProgressDialog,Dialog } from 'react-native-simple-dialogs';

import AsyncStorage from '@react-native-community/async-storage';


import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
 
 

function Login ({navigation}){
 
  
  const[alerted,isalerted]=useState(false)
  const[authError,setAuthError]=useState(false)
  const[accInactive,isAccInactive]=useState(false)
  const[loginFail,didLoginFail]=useState(false)
  const[login,didLogin]=useState(false)
  const[email,setemail]=useState(email)
  const[ClientID,setClientID]=useState(ClientID)
  const[Password,setPassword]=useState(Password)
 
 

我在这里尝试设置异步存储的项目

  function LoginButton () {
    AsyncStorage.setItem("MyEmail",email)
  AsyncStorage.setItem("MyPassword",Password)
  AsyncStorage.setItem("MyClientID",ClientID)

    fetch('https://www.SITE.co.za/app-login.asp?ClientID='+ClientID+'&Username='+email+'&Pwd='+Password)
    .then((response) => response.json())
    .then((responseJson) => {
      //Successful response from the API Call
      
     
      if (JSON.stringify(responseJson).includes("Login Success")){
      
        {isalerted(true),didLogin(false),isLoggedIn('Yes')}
        
     
    
      
       
      }
    else if (JSON.stringify(responseJson).includes("No Authentication Details Received"))
    {
     {setAuthError(true)}
  
    }
   else  if (JSON.stringify(responseJson).includes("Account Not Active"))
    {
     {isAccInactive(true)}
  
    }
  else  if (JSON.stringify(responseJson).includes("Login Details Incorrect"))
    {
      {didLoginFail(true)}
  
    }
     
    })
    .catch((error) => {
      console.error(error);
    });
  }
  
  function navButton(){
   
 
   
    navigation.navigate('Dashboard')
    isalerted(false)
  }

     return (
        <KeyboardAwareScrollView keyboardShouldPersistTaps='handled'>
<SafeAreaView>
<ProgressDialog
    visible={didLogin}
    activityIndicatorColor="#4994CF"
    activityIndicatorSize="large"
    animationType="slide"
    title="Logging in"
    message="Please, wait..."
/>

<Dialog
    visible={alerted}
    
    onTouchOutside={''} >
    <View>
      <Text style={{color:'green',fontSize:20, marginBottom:10 ,textAlign:"center"}}>Login Success</Text>
      <Button
      title="Continue To Dashboard"
      onPress={navButton}
      />
       
    </View>
</Dialog>
 <Dialog
    visible={authError}
    
    onTouchOutside={''} >
    <View>
      <Text style={{color:'red',fontSize:20, marginBottom:10 ,textAlign:"center"}}>No Authentication Details Received</Text>
      <Button
      title="OK"
      onPress={ ()=>setAuthError(false)}
      />
       
    </View>
</Dialog>
<Dialog
    visible={accInactive}
    
    onTouchOutside={''} >
    <View>
      <Text style={{color:'red',fontSize:20, marginBottom:10 ,textAlign:"center"}}>Account Not Active</Text>
      <Button
      title="OK"
      onPress={ () =>isAccInactive(false)}
      />
       
    </View>
</Dialog>
<Dialog
    visible={loginFail}
    
    onTouchOutside={''} >
    <View>
      <Text style={{color:'red',fontSize:20, marginBottom:10 ,textAlign:"center"}}>Login Details Incorrect</Text>
      <Button
      title="OK"
      onPress={()=> didLoginFail(false)}
      />
       
    </View>
</Dialog> 


<View style={{flexDirection:"row"}}>
        <Image source={{uri: 'https://www.SITEe.co.za/images/smartpractice-logo-02.png'}}
       style={{marginTop:35,paddingTop:10
      , height: 80,width:360,flexWrap:'wrap',resizeMode:"contain" }} /> 
<Text style={{textAlign:'center',color:"#4994CF", marginTop:35}}>Beta</Text>
</View>
<View style={{width:'95%',alignContent:'center',marginLeft:10}}>
  <Text style={{fontSize:20,color:'grey'}}>Welcome to the SmartPractice Beta App,
    Please Login below with your SmartPractice login Details
  </Text>
</View>

        <View style={{marginTop:10,alignItems:"center"}}>
          <View style={styles.Label}>
          
        <Text style={styles.LabelText}>Email</Text>
        </View>
          <TextInput onChangeText={(text)=>setemail(text)} autoCompleteType='email' placeholder="Email"   style={{width:'95%',height:40,backgroundColor:'#d8d8d8',marginBottom:3, paddingHorizontal: 10,marginTop:5}}/>
          <View style={styles.Label}>
        <Text style={styles.LabelText}>Password</Text>
        </View>
          <TextInput onChangeText={(text)=>setPassword(text)} autoCompleteType="password" secureTextEntry={true} placeholder="Password"   style={{width:'95%',height:40,backgroundColor:'#d8d8d8',marginBottom:3, paddingHorizontal: 10,marginTop:5}}/>
          <View style={styles.Label}>
          <Text style={styles.LabelText}>ClientID</Text>
         </View>
          <TextInput onChangeText={(text)=>setClientID(text)} keyboardType="numeric" placeholder="ClientID"  style={{width:'95%',height:40,backgroundColor:'#d8d8d8',marginBottom:3, paddingHorizontal: 10,marginTop:5}}/>
       <View style={{marginTop:5,width:'95%'}}>   
       <View style={{width:'95%',alignContent:'center',marginLeft:10,marginBottom:10}}>
  <Text style={{fontSize:15,color:'grey'}}>ClientID : Log into Smartpractice on the internet and use the 4 digit number at the end of your URL (internet Address) of your login screen 
  </Text>
  </View>
<Button 

        title="Save"
        onPress={LoginButton}
      />
      </View>
        </View>
        </SafeAreaView>
        </KeyboardAwareScrollView>
      );
   
  
       }
      

  const styles = {
    container: {
      
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      marginTop:5
    },
    Label: {
      backgroundColor:'#A6A5A4',
      color:"white",
      textAlign: "center",
       marginTop:2,
       fontSize: 15,
       width:'100%',
       
       
  
    },
    alertmessage:{
      color:'green'
    },
    LabelText: {
      
      backgroundColor:'#A6A5A4',
      color:"white",
      textAlign: "center",
       fontSize: 20,
     
       
       
  
    },
  };

export default Login;

这里是我试图检索一些数据的地方 (Dashboard.js)

import React, {Component } from 'react'
import { View, Text,Image,TouchableOpacity,StyleSheet,SafeAreaView,} from 'react-native'


import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'

import AsyncStorage from '@react-native-community/async-storage';

function Dashboard ({navigation}){
  
  

   let MyClientID = AsyncStorage.getItem("MyClientID")

   

  console.log(global.mail)
    
      return (
        <KeyboardAwareScrollView keyboardShouldPersistTaps='handled'>
        <SafeAreaView style={styles.container}>
        <View style={{flexDirection:"row"}}>
        <Image source={{uri: 'https://www.site.co.za/images/smartpractice-logo-02.png'}}
       style={{marginTop:5,paddingTop:10
      , height: 80,width:360,flexWrap:'wrap',resizeMode:"contain" }} /> 
<Text style={{textAlign:'center',color:"#4994CF", marginTop:35}}>Beta</Text>
</View>
<Image source={{uri: 'https://www.site.co.za/images/logos/'+MyClientID+'/main-dashboard-logo.png'}}
       style={{marginTop:5,paddingTop:10
      , height: 70,width:'100%',flexWrap:'wrap',resizeMode:"contain",marginLeft:5 }} /> 
<View style={{justifyContent:"center", marginTop:6}}>
 <Text style={styles.DateLabel}>Description</Text>
 
 </View> 
         

          <TouchableOpacity style={styles.ImageButton}
        onPress={() => navigation.navigate('Incidental Time')}
      >
<Image style={{flexWrap:'wrap',resizeMode:"contain",maxHeight:120,maxWidth:120 }}  tintColor='#4994CF' source={require('../../icons/time_log.png')} />
<Text style={styles.TextStyle}>Time Log</Text>

      </TouchableOpacity>
        </SafeAreaView> 
        </KeyboardAwareScrollView>
      
      );
    }
  

    const styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
    },
    textInput: {
      backgroundColor:'#A6A5A4',
      color:"white",
      textAlign: "center",
       marginTop:5,
       fontSize: 20,
       marginBottom:5
      ,marginLeft:1
  
    },
    DateLabel: {
      backgroundColor:'#A6A5A4',
      color:"white",
      textAlign: "center",
       marginTop:2,
       fontSize: 20,
       paddingLeft:140,
       paddingRight:140,
       width:'100%',
       marginBottom:10
  
    },
    ImageButton: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
    },
    TextStyle:{
      color:"grey"
    
    }
  });

export default Dashboard;

我尝试在 useeffect 中设置项目,将值包装在 STRING() 中的 setitems 中 尝试在 set/getitem 之前制作附加了异步的函数和 const 以及 await 我已经检查了几个小时,none 的答案或问题对我有帮助

我真的不知道我做错了什么 我遵循了 asynstorage 文档,甚至从文档中复制代码也不起作用

我没有收到错误,这两天一直在努力解决像本地存储这样简单的问题 请帮助

与您的查询无关,但老实说,根据我的经验,Expo 是您最不想在项目中使用的东西。特别是如果您稍后将引入本机依赖项。

我知道你可以使用 ExpoKit,但仍然......不要使用 Expo

您可以使用 NativeBase 中的 Content 而不是 KeyboardAwareScrollView

对于您的查询,AsyncStorage 中的所有方法都是异步的。所以记得使用 await 来获取你的值

async function fetchLocal(){
    const persisted = await AsyncStorage.getItem("persisted");
    
    if(persisted){
        console.log(JSON.parse(persisted)); // Oh! the value for these persisted keys needs to be a string, so make sure to String()|.toString()|JSON.stringify objects you wanna serialize. 
    }
}

AsyncStorage的getItem和setItem都是Promise,需要使用await或者callback。 对于 setItem,当前的用法是可以的,但对于 getItem,这是必不可少的。 还需要在useEffect中使用getItem,将MyClientID设为state。

尝试使用以下代码代替您的 Dashborad.js:

import React, {Component} from 'react';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  StyleSheet,
  SafeAreaView,
} from 'react-native';

import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';

import AsyncStorage from '@react-native-community/async-storage';

function Dashboard({navigation}) {
  const [MyClientID, setMyClientID] = useState('');

  useEffect(() => {
    AsyncStorage.getItem('MyClientID').then((myClientID) => {
      setMyClientID(myClientID);
    });
  }, []);

  console.log(global.mail);

  return (
    <KeyboardAwareScrollView keyboardShouldPersistTaps="handled">
      <SafeAreaView style={styles.container}>
        <View style={{flexDirection: 'row'}}>
          <Image
            source={{
              uri: 'https://www.site.co.za/images/smartpractice-logo-02.png',
            }}
            style={{
              marginTop: 5,
              paddingTop: 10,
              height: 80,
              width: 360,
              flexWrap: 'wrap',
              resizeMode: 'contain',
            }}
          />
          <Text style={{textAlign: 'center', color: '#4994CF', marginTop: 35}}>
            Beta
          </Text>
        </View>
        <Image
          source={{
            uri:
              'https://www.site.co.za/images/logos/' +
              MyClientID +
              '/main-dashboard-logo.png',
          }}
          style={{
            marginTop: 5,
            paddingTop: 10,
            height: 70,
            width: '100%',
            flexWrap: 'wrap',
            resizeMode: 'contain',
            marginLeft: 5,
          }}
        />
        <View style={{justifyContent: 'center', marginTop: 6}}>
          <Text style={styles.DateLabel}>Description</Text>
        </View>

        <TouchableOpacity
          style={styles.ImageButton}
          onPress={() => navigation.navigate('Incidental Time')}>
          <Image
            style={{
              flexWrap: 'wrap',
              resizeMode: 'contain',
              maxHeight: 120,
              maxWidth: 120,
            }}
            tintColor="#4994CF"
            source={require('../../icons/time_log.png')}
          />
          <Text style={styles.TextStyle}>Time Log</Text>
        </TouchableOpacity>
      </SafeAreaView>
    </KeyboardAwareScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  textInput: {
    backgroundColor: '#A6A5A4',
    color: 'white',
    textAlign: 'center',
    marginTop: 5,
    fontSize: 20,
    marginBottom: 5,
    marginLeft: 1,
  },
  DateLabel: {
    backgroundColor: '#A6A5A4',
    color: 'white',
    textAlign: 'center',
    marginTop: 2,
    fontSize: 20,
    paddingLeft: 140,
    paddingRight: 140,
    width: '100%',
    marginBottom: 10,
  },
  ImageButton: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  TextStyle: {
    color: 'grey',
  },
});

export default Dashboard;