首页 > 解决方案 > 如何在 react-native 中每次启动应用程序时增加 asyncStorage 值?

问题描述

每次启动应用程序时,我都想从 AsyncStorage 增加 myKey 变量。但就我而言,价值永远不会改变。每次应用启动时我都会得到 1。

任何人都知道如何增加 asyncStorage 的变量。

这是我的代码

 import React, { Component } from 'react';
 import { AsyncStorage, View, Text } from 'react-native';

 export default class App extends Component {
   constructor() {
     super();
     this.state = {
       myKey: 0
      }
    }

  componentWillMount() {
    this.saveData();
 }

 saveData() {
   AsyncStorage.setItem('myKey', this.state.myKey + 1);
   this.setState({'myKey': JSON.parse(this.state.myKey + 1)});
 }

 componentDidMount() {
   AsyncStorage.getItem('myKey').then((value) => {
    this.setState({'myKey': value});
  });
  console.log(this.state.myKey);
}

render() {
   return (
      <View>
        <Text>Hello World</Text>
     </View>
    );
  }
}

在此处输入图像描述

标签: react-nativeincrementlaunchasyncstorage

解决方案


ComponentWillMount 在 ComponentDidMount 之前触发,因此您始终将您的密钥设置为 1(因为您的 state.key =0),然后您获取存储密钥并使用 1 更新您的状态。此外,您只能将字符串值保存在 AsyncStorage 中,因此您必须先从 string 转换为 int 以进行计算,然后从 int 转换为 string 以保存值。我会这样做:

async componentDidMount() {
    let key = parseInt(await AsyncStorage.getItem('myKey'));
    AsyncStorage.setItem('myKey', (key + 1).toString());
});

推荐阅读