首页 > 解决方案 > 警告:可能未处理的 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) });
    });
  }

标签: jsonreactjsreact-nativeparsingpromise

解决方案


您可以在 .then 中使用 if 块

AsyncStorage.getItem("KEY").then((value) => {
          if(value){
          this.setState({ present_count: JSON.parse(value || this.state.present_count) });
        }
        });

推荐阅读