异步存储将Promice转换为JSON格式
这段代码在不同的地方给出了两个不同的输出,经过多次尝试后,我无法理解。请帮帮我,我是新手。 log(文件)此函数提供一个输出和console.warn(jsonValue!=null?JSON.parse(jsonValue):null);给出另一个输出异步存储将Promice转换为JSON格式,json,react-native,react-native-android,react-native-ios,asyncstorage,Json,React Native,React Native Android,React Native Ios,Asyncstorage,这段代码在不同的地方给出了两个不同的输出,经过多次尝试后,我无法理解。请帮帮我,我是新手。 log(文件)此函数提供一个输出和console.warn(jsonValue!=null?JSON.parse(jsonValue):null);给出另一个输出 storeData = async () => { try { const jsonValue = JSON.stringify( { "
storeData = async () => {
try {
const jsonValue = JSON.stringify(
{
"Belgin":"Test Check"
}
)
await AsyncStorage.setItem('BelginKey', jsonValue)
} catch (e) {
console.log(e)
}
}
getData = async () => {
try {
const jsonValue = await AsyncStorage.getItem('BelginKey')
console.warn( jsonValue != null ? JSON.parse(jsonValue) : null); // Output as {"belgin":"Text Test"}
} catch(e) {
console.log(e)
}
}
change_and_display=()=>{
const files = this.getData()
console.log(files) // Output as {"_40": 0, "_55": null, "_65": 0, "_72": null}
}
render(){
return(
<SafeAreaView style={styles.container} >
<TouchableOpacity onPress={this.storeData} style={{height:"10%",width:"100%",backgroundColor:"#000"}}>
<Text style={{color:"#FFF"}}>Click This To Add Value</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.change_and_display} style={{height:"10%",width:"100%",backgroundColor:"#a1a1a1"}}>
<Text style={{color:"#FFF"}}>Click This To Get Value</Text>
</TouchableOpacity>
<Text></Text>
</SafeAreaView>
)
}
storeData=async()=>{
试一试{
const jsonValue=JSON.stringify(
{
“贝尔金”:“测试检查”
}
)
等待AsyncStorage.setItem('BelginKey',jsonValue)
}捕获(e){
控制台日志(e)
}
}
getData=async()=>{
试一试{
const jsonValue=await AsyncStorage.getItem('BelginKey'))
console.warn(jsonValue!=null?JSON.parse(jsonValue):null);//输出为{“belgin”:“Text Test”}
}捕获(e){
控制台日志(e)
}
}
更改和显示=()=>{
const files=this.getData()
log(files)//输出为{“_40:0”,“_55:null”,“_65:0”,“_72:null}
}
render(){
返回(
单击此按钮可添加值
单击此按钮以获取值
)
}
}您忘了在
getData()中返回值,这就是它不起作用的原因
另外,不要忘记异步函数返回一个承诺,因此要获取getData()的值,请使用async/await或.then()命令
然后,当您使用OnPress()
时,不要忘了始终在其中放置一个箭头函数,以便它仅在按下时渲染
示例:onPress={()=>this.storeData}
Sir,即使返回,也会得到相同的输出。{“_40:0”,“_55:null”,“_65:0”,“_72:null}您是否尝试通过异步等待函数获取文件?是的,先生,成功了!