我在开发反应原生移动应用程序时遇到此错误 .
fetchDB
函数将返回一个promise
fetchDB(key) {
try {
AsyncStorage.getItem(key, result => {
return result;
});
} catch (error) {
console.log(error);
}
}
}
使用 .then()
从返回的promise中获取值
getUserName = () => {
var user = Storage.fetchDB("username");
user.then(res => {
alert(res);
});
};
它渲染红屏有错误
undefined不是对象
1 回答
1) 您需要显式返回promise函数 . 可以在catch回调中处理失败情况:
2) Point(1)仅在
AsyncStorage.getItem
真正返回promise时有效 . 如果不是这样,那么您需要将AsyncStorage.getItem
方法更新为基于承诺 . 如果您无法访问该方法或不想触摸它,也可以通过以下方式更新fetchDB
函数来解决问题:3) 我甚至会说因为es6 Promises性质你不需要try-catch:
最后
.catch
处理从fetchDB
Promise抛出的任何错误 .