[英]handling 2nd response when doing multiple GET requests in React
I've manage to pass the first response into the state name data (this.state.data) of the component. 我设法将第一个响应传递到组件的状态名称数据(this.state.data)。 But when I trying doing a second request for data1 from another API, it's not showing up. 但是,当我尝试从另一个API再次请求data1时,它没有显示出来。 Both responses are good from checking in dev tool and the first one I can use the data. 这两个响应都可以从检入开发工具中获得,并且第一个我可以使用数据。
class WeatherApp extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
data: [],
data1: []
};
}
componentDidMount() {
Promise.all([
fetch("weatherAPI.php"),
fetch("weatherAPIToday.php")
]).then(([res, res1]) => res.json())
.then((result, result1) => {
this.setState({
isLoaded: true,
data: result,
data1: result1
}, console.log(result));
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
}
Because both res and res1 return a promise, all you have to do is wrap them both in a Promise#all 由于res和res1都返回promise,因此您要做的就是将它们都包装在Promise#all中
Promise.all([
fetch("weatherAPI.php"),
fetch("weatherAPIToday.php")
]).then(([res, res1]) => Promise.all(res.json(), res1.json()))
.then((result, result1) => {
this.setState({
isLoaded: true,
data: result,
data1: result1
}, console.log(result));
})
.catch(error => {
this.setState({ isLoaded: true, error });
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.