如何在异步存储中存储变量?

时间:2019-01-19 16:03:27

标签: react-native asyncstorage

我目前正在学习本机。

我正在尝试将变量存储在scriptone.js中的异步存储中,并在scripttwo.js中调用

但是我无法将变量存储在scriptone.js中

我在scriptone.js中导入的内容:

import React, { Component, BackAndroid } from "react";
import { AsyncStorage } from 'AsyncStorage';
import { View, Text, StyleSheet, Button, Image, TouchableOpacity, TextInput, Alert} from "react-native";

这是我在scriptone.js中的代码的一部分

class SettingScreen extends Component {
  state = {
      a: '70',
      b: '',
      c: '',
    }; 

onPressButton = () => {
      if (this.state.a == this.state.aa) {     
        this.setState({ b: this.state.a });
        this.storeData();
      }
       else {
        Alert("Try Again");
      }
    }

   storeData(){
        const {a} = this.state;
        let  mynum : a;
        AsyncStorage.setItem('array',mynum)
        Alert("Saved");
   }

...

错误显示:

"undefined is not an object(evaluating '_AsyncStorage.AsyncStorage.setItem')

我可以知道是什么问题吗? 谢谢。

1 个答案:

答案 0 :(得分:0)

AsyncStorage

通常要先使用AsyncStorage,首先将其导入文件顶部,文档中指出应按以下方式导入它:

import { AsyncStorage } from 'react-native';

您可以在这里看到https://facebook.github.io/react-native/docs/asyncstorage

显然,您应该删除上一个导入语句

import { AsyncStorage } from 'AsyncStorage'; 

,因为将其保留会导致名称冲突。

保存到AsyncStorage

保存到AsyncStorage是异步任务,因此您应该使用async/await函数,这意味着您应该更新storeData()函数。您可以参阅https://facebook.github.io/react-native/docs/asyncstorage文档,了解如何执行此操作。

storeData = async () => {
  const {a} = this.state;
  let  mynum = a;
  try {
    await AsyncStorage.setItem('array', mynum)
    Alert("Saved");
 } catch (err) {
    console.warn(err);
 } 
}

设置状态

接下来,当您设置状态时,您看起来可能会陷入比赛状态。 setState将项目设置为状态需要花费时间。因此,当您致电

this.setState({ b: this.state.a });

在您致电时可能实际上尚未设置状态

this.storeData();

导致将错误值存储在AsyncStorage中。

要克服这个问题,您可以采用几种方法来解决

  1. 将setState与回调一起使用
  2. 将变量作为参数存储到this.storeData()

将setState与回调一起使用

本文详细介绍了如何将setState与回调https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296一起使用,但是您可以将onPressButton重构为类似的内容

onPressButton = () => {
  if (this.state.a == this.state.aa) {     
    this.setState({ b: this.state.a }, async () => { await this.storeData(); });
  } else {
    Alert("Try Again");
  }
}

这将确保this.storeData()在状态更新之前不会运行。

传递变量以将其存储为参数

这需要重构storeData()函数以获取参数

storeData = async (mynum) => {
  try {
    await AsyncStorage.setItem('array',mynum)
    Alert("Saved");
 } catch (err) {
    console.warn(err);
 } 
}

现在要使用此功能,我们必须更新您的onPressButton,请注意,我们将要存储的值传递给storeData,这意味着我们不再需要从{{ 1}}

storeData

从AsyncStorage检索

这也是异步任务,需要onPressButton = async () => { if (this.state.a == this.state.aa) { this.setState({ b: this.state.a }); await this.storeData(this.state.a); } else { Alert("Try Again"); } } 。要获取存储的字符串,只需将正确的密钥传递给async/await函数

retrieveData