首页 > 解决方案 > React Native 可能未处理的 Promise 拒绝

问题描述

我正在尝试使用 React Native 的 fetch 函数从 API 获取值。然后将从 JSON 检索到的值标记为 Millions 、 Billions ... 等。

JSON文件

{
  "value": 92060,
  "new": 1
} 

为了做我想做的事,我使用了下面的代码。

async componentDidMount() {

let data =  await fetch('https://demo614535421.mockable.io/getData')
.then((response) => response.json())
.then((responseJson) => {
  this.setState({
    grossRev : this.getCodedValues(responseJson.grossRevenue)
  })

})
.catch((error) => {
  console.error(error);
});
this.setState({ wowData: true });
return data;

}

getCodedValues()功能,

getCodedValues(value)
{
  console.log(Math.abs(Number(value)));
}

在我检查数百万和数十亿之前,iOS 模拟器开始显示错误消息,

Undefined is not an Object (evaluating '_reactNative.Math.abs')

在捕获数据时,我在这里使用 async 和 await 来保存函数。但似乎在getCodedValues函数value参数中仍然是undefined

问题

  1. 我该如何解决这个问题并进行算术计算?

标签: javascriptreact-native

解决方案


这个怎么样?这仅使用 async/await 并且不处理 then/catch,因为当您使用 await 时,它会等待 fetch 返回响应。

async componentDidMount() {
   try {
      let response =  await fetch('https://demo614535421.mockable.io/getData');
      let responseJson = response.json();
      this.setState({
         grossRev: this.getCodedValues(responseJson.grossRevenue)
      })
   }catch(err){
      console.log(err);
   }
}

推荐阅读