Javascript Reactjs:避免1个API失败的最佳方法影响react componentDidMount内多个API调用的其他API调用
我正在编写一个react组件,它需要在componentDidMount中调用两个或更多的API,如下所示 2个API调用将更新2个不同的状态,因此将重新呈现两个不同的子组件 然而,我相信我写的不是最好的方法,因为一个API的潜在故障也会导致另一个API的故障。因为它们是放在一起的 我想问,处理这种情况的最佳办法是什么?为避免1 API故障影响componentDidMount内多个API调用的其他API调用?谢谢你的帮助Javascript Reactjs:避免1个API失败的最佳方法影响react componentDidMount内多个API调用的其他API调用,javascript,reactjs,Javascript,Reactjs,我正在编写一个react组件,它需要在componentDidMount中调用两个或更多的API,如下所示 2个API调用将更新2个不同的状态,因此将重新呈现两个不同的子组件 然而,我相信我写的不是最好的方法,因为一个API的潜在故障也会导致另一个API的故障。因为它们是放在一起的 我想问,处理这种情况的最佳办法是什么?为避免1 API故障影响componentDidMount内多个API调用的其他API调用?谢谢你的帮助 import React from "react";
import React from "react";
import * as api from "api";
import moment from "moment";
class ExchangeRate extends React.Component {
constructor(props) {
super(props);
this.state = {
dataCurrency: [],
dataTrend: []
}
};
async componentDidMount() {
const date = moment().subtract(1, "month").format("YYYY-MM-DD");
const exRateTrendData = await api.exchangeRate.getTrend();
const exRateData = await api.exchangeRate.get(date);
this.setState({
dataCurrency: exRateData,
dataTrend: exRateTrendData,
});
};
render() {
return (
<>
<Component1 depending on dataCurrency />
<Component2 depending on dataTrend />
</>
)
};
};
从“React”导入React;
从“api”导入*作为api;
从“时刻”中导入时刻;
类ExchangeRate扩展React.Component{
建造师(道具){
超级(道具);
此.state={
数据货币:[],
数据趋势:[]
}
};
异步组件didmount(){
常量日期=时刻()。减去(1,“月”)。格式(“YYYY-MM-DD”);
const exRateTrendData=wait api.exchangeRate.getTrend();
const exRateData=等待api.exchangeRate.get(日期);
这是我的国家({
数据货币:exRateData,
dataTrend:exRateTrendData,
});
};
render(){
返回(
)
};
};
使用async/await
的最佳实践是将代码包装在try{}catch(){}
中(您可以阅读更多相关内容),因为您可以在componentDidMount
中将两个调用彼此分开,这样它们就可以分别失败:
async componentDidMount() {
const date = moment()
.subtract(1, "month")
.format("YYYY-MM-DD")
try {
const exRateTrendData = await api.exchangeRate.getTrend()
this.setState({
dataTrend: exRateTrendData,
})
} catch (e) {
console.log("something wrong with exRateTrendData call")
}
try {
const exRateData = await api.exchangeRate.get(date)
this.setState({
dataCurrency: exRateData,
})
} catch (e) {
console.log("something wrong with exRateData call")
}
}
在promise catch中返回的将是promise的解析值,现在即使请求失败,您的promise也不会失败:
const exRateTrendData=wait api.exchangeRate.getTrend().catch(error=>failedValueForexRateTrendData)