javascript - 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
?
问题
- 我该如何解决这个问题并进行算术计算?
解决方案
这个怎么样?这仅使用 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);
}
}
推荐阅读
- python - Codecademy Python 2 石头、纸、剪刀
- javascript - 带有 Jquery 的轮播
- python - 将 python 连接到 cx_oracle 时出现问题 - 错误 ORA-01804
- reactjs - 修复了特定 Next.js 路由上的侧边菜单
- excel - 在 VBA 中访问私有变量给出“未找到变量”
- html - 在移动设备和桌面上正确显示 HTML/CSS
- docker - 如何在新的 GKE 节点上缓存大型 Docker 映像?
- dialogflow-es-fulfillment - Webhook 调用失败。错误:DEADLINE_EXCEEDED。尽管请求延迟花费了 4991 毫秒
- flutter - 容器的不可见部分
- vb.net - VB.NET 中的 FindWindowEx