好吧,问题是你打电话给func
this.readData()
在渲染中,该函数本身正在调用
setState
无论何时调用,都会更改状态,从而触发对组件的重新呈现。所以在这种情况下,您在代码中引起了一个无限循环,因为
设置状态
调用呈现,然后调用
设置状态
你的记忆又一次耗尽了。
若要快速修复此问题,可以从渲染中移除函数调用,并将其添加到按钮中,以便仅在需要时调用它。像这样:
import React, { Component} from 'react';
import {Image, Platform, StyleSheet, Text, View, Button} from 'react-native'
import { AsyncStorage } from "react-native"
export default class StorageDemo extends Component{
constructor(props){
super(props)
this.state = {
isLoaded: false,
visitTimes: 0
}
}
readData = async () => {
try{
const result = await AsyncStorage.getItem("visitTimes")
this.setState(
{
visitTimes: result,
isLoaded: true
}
)
console.info("== loaded, this.state: ")
}catch(error){
console.error(error)
}
}
render() {
if(this.state.isLoaded){
return(
<View>
<Text>Loaded! {this.state.visitTimes} </Text>
<Button
onPress={() => {
AsyncStorage.setItem("visitTimes", "100")
this.setState({isLoaded: false})
}}
title="Set Storage Item"
/>
</View>
)
}else{
return(
<View>
<Button
onPress={this.readData}
title="Load from async storage"></Button>
</View>
)
}
}
}
试试这个,这应该会给你从本地存储的价值!