如何在React Native中从异步存储中正确获取数据?

时间:2019-12-28 05:51:09

标签: reactjs react-native local-storage asyncstorage

我正在尝试通过异步存储加载和检索本地数据。我已经在页面上布置了当前设置,但是无法检索数据。单击存储数据后,当我收到有关数据的通知时,数据肯定已保存。但是当我继续调用数据时,它返回一个空值。我在这里做错什么了吗?

const STORAGE_KEY = '@save_enableauto'

    state={
        enableAuto:false
    }

    _storeData = async enableAuto => {
        try {
          let x = toString(enableAuto);
          await AsyncStorage.setItem(STORAGE_KEY, x)
          alert('Data successfully saved!')
          //this.setState({ enableAuto: x })
        } catch (e) {
            console.log(e)
          alert('Failed to save name.')
        }
      }

    _retrieveData = async () => {
        console.log('trying to call data')
        try {
          const enableAuto = await AsyncStorage.getItem('STORAGE_KEY');
          console.log(enableAuto)
          if (enableAuto !== null) {
            // We have data!!
            console.log(enableAuto);
          }
        } catch (error) {
            alert('failed to load previous settings.')
          // Error retrieving data
        }
    };

   ...

   <Button title={'Store Data'} onPress={() => this._storeData(this.state.enableAuto)}/>
                        <Button title={'call Data'} onPress={() => this._retrieveData()}/>
                    </View>    
                        <View>
                            <CheckBox
                                value={this.state.enableAuto}
                                onValueChange={() => this.setState({ checked: !this.state.enableAuto })}
                            />

1 个答案:

答案 0 :(得分:1)

上面的错误是在存储时,您正在设置:

await AsyncStorage.setItem(STORAGE_KEY, x)

此处STORAGE_KEY表示值@save_enableauto

但是在检索数据时

const enableAuto = await AsyncStorage.getItem('STORAGE_KEY');

您将'STORAGE_KEY'作为字符串提供,因此这意味着其引用'STORAGE_KEY'并且它没有任何存储的值。试试这个

const enableAuto = await AsyncStorage.getItem(STORAGE_KEY);

希望有帮助。毫无疑问