json - 警告:可能未处理的 Promise Rejection
问题描述
当我第一次打开我新构建的应用程序时,会出现以下警告。我认为这是因为AsyncStorage.getItem("KEY")
当应用程序第一次运行时,key in 没有任何价值。我该如何处理这个承诺拒绝?
this.state = {
subjects: [],
text: "",
present_count: [0, 0, 0, 0, 0, 0, 0],
total_count: [0, 0, 0, 0, 0, 0, 0],
present: 0,
total: 0
}
componentDidMount() {
this._isMounted = true;
Subjects.all(subjects => this.setState({ subjects: subjects || [] }));
AsyncStorage.getItem("PRESENT_COUNT").then((value) => {
this.setState({ present_count: JSON.parse(value || this.state.present_count) });
});
AsyncStorage.getItem("TOTAL_COUNT").then((value) => {
this.setState({ total_count: JSON.parse(value || this.state.total_count) });
});
AsyncStorage.getItem("PRESENT").then((value) => {
this.setState({ present: JSON.parse(value || this.state.present) });
});
AsyncStorage.getItem("TOTAL").then((value) => {
this.setState({ total: JSON.parse(value || this.state.total) });
});
}
解决方案
您可以在 .then 中使用 if 块
AsyncStorage.getItem("KEY").then((value) => {
if(value){
this.setState({ present_count: JSON.parse(value || this.state.present_count) });
}
});
推荐阅读
- c# - 从链接下载文件已发送到电子邮件
- r - Picking top n% percent of elements from matrix rows, different number of elements on each row
- regex - 替换除表情符号外的所有非字母数字字符
- ruby-on-rails - 初始化后是否可以设置 Selenium::Driver::Proxy
- android - 如何将editText中的字母大写?
- machine-learning - 为什么在 inception 网络中内核大小变大而特征图的空间大小变小?
- r - 使用空格和大写字母拆分字符串
- rsyslog - rsyslog 通过 ssl 流利
- ios - 图像建议不起作用 Xcode 10
- maven - 您可以使用下面的代码片段来实现缺少的步骤