reactjs - 当onPress菜单反应原生时如何保存价值?
问题描述
我是 react-native 的新手,我正在测试单击按钮时如何保存值,这里是带有两个按钮的菜单
<MenuItem onPress={this.hideMenu}>Menu item 1</MenuItem>
<MenuItem onPress={this.printValue}>Menu item 2</MenuItem>
以下几行在我的主要活动中
_storeData = async () => {
try {
await AsyncStorage.setItem('test', 'I like to save it.');
} catch (error) {
// Error saving data
}
};
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('test');
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
};
hideMenu = () => {
this._storeData();
this._menu.hide();
};
printValue = () => {
this._retrieveData();
alert(this._retrieveData.value);
}
上面的代码不起作用,有人知道怎么做吗?
解决方案
你做了一个很好的尝试,但你错过了一些事情。
你应该await
在你的函数调用前面,因为它们是异步函数。此外,您没有从您的_retrieveData
函数中返回任何内容。
await
在正确的地方添加- 返回
value
from_retrieveData
函数,您可能希望根据返回的内容返回不同的值。您可以重构它以使用承诺。
这是您的代码及其更新。
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('test');
if (value !== null) {
// We have data!!
console.log(value);
return value; // <- return the value that you have found
}
// you may wish to return something if no value is found
} catch (error) {
// Error retrieving data
// you may wish to return something if an error occurs
}
};
hideMenu = () => {
await this._storeData(); // <- add await here
this._menu.hide();
};
printValue = () => {
let value = await this._retrieveData(); // <- add await and capture the returned value
alert(value);
}
推荐阅读
- node.js - Windows-build-tools 安装
- url - 如何使用 AppleScript 从电子邮件中检索 URL?
- javascript - 切换值未作为参数传入 url
- python - 如何在 Kivy 开发的应用程序上从剪贴板按钮编程复制到和粘贴
- xamarin - 编辑器将文本环绕至少一次问题
- html - 如何在模糊时获取输入元素的值?
- c# - 序列化 XML 响应后的空对象数组
- css - 如何将一个 div 放入模态的另一个 div
- angular - 由于崩溃 Ionic 5 无法打开“DetailPage”
- javascript - 渲染不同的组件时无法更新组件(useState)