react-native - 如何在 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>
);
}
}
解决方案
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());
});
推荐阅读
- c# - PDFClown nuget 包无法加载程序集
- google-cloud-platform - 域 SSL 不起作用,我该怎么办?
- php - 为什么我的电子邮件和数据库会出现 2 个不同的值?
- optimization - 八度:quadprog 索引问题?
- c++ - 使用带有自动声明的 lambdas 与就地?
- c# - 动态加载 XAML 控件时无法创建未知类型“画布”
- javascript - 同位素多级过滤不起作用
- python - 使用 python 和 beautifulsoup 对 Google Ads 进行网页抓取
- java - 我不知道为什么我的下一个 If 语句只是我最后的手段!JAVA
- c# - 后台线程和对话框