json - AsyncStorage 将 Promice 转换为 JSON 格式
问题描述
经过大量尝试后,代码在不同的地方给出了两个不同的输出,我无法弄清楚。请帮助我,我是 React Native 的新手。console.log(files) 这个函数给出一个输出和 console.warn( jsonValue != null ? JSON.parse(jsonValue) : null); 给出另一个输出
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>
)
}
}
解决方案
您忘记在它中返回您的价值,getData()
这就是它不起作用的原因。
另外不要忘记异步函数返回一个 Promise,因此要获取值 getData() 的值,请使用 async/await 或 .then()
然后当你使用时OnPress()
,不要忘记总是在里面放一个箭头函数,这样它只会在你按下时呈现。
例子 :onPress={() => this.storeData}
推荐阅读
- sql-server - SQL Server Express 2016 用户在 SSMS 中工作,但不能通过内部 IP 从应用程序中工作
- java - 我有一个包含在 ScrollView 中的 ListView 以在标题下显示字符串列表,但无法正确显示
- javascript - 如何通过 javascript 拦截所有 AJAX(xhr 和 fetch) 请求?
- lua - LUA 字符串,删除非字母数字或空格
- r - 我的循环正常运行,但在单个文件上突然失败
- cron - 等待 5 分钟 ---- 运行作业 ---- 作业完成 ---- 等待 5 分钟 .... 等等
- python - 如何从列表列表中创建矩阵彩色图(Python)
- javascript - 在制作动画时对值进行 React Native 访问
- mysql - 优雅地忽略具有 NULL 值的无效日期
- bots - 如何将反应存储到 quick.db