[英]React Native How to get multiple APIs at the same time?
For my project, I have to get several APIs in my projects, these APIs are linked to the others, ie they have the same data ...对于我的项目,我必须在我的项目中获取多个 API,这些 API 与其他 API 相关联,即它们具有相同的数据......
Here is my code这是我的代码
export default class App extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
Promise.all([
getData(),
getData('?page=2'),
])
.then(([dataSource1, dataSource2]) => {
this.setState({
isLoading: false,
isLoading2: false,
dataSource1,
dataSource2,
});
})
.catch((error) => {
// handle errors
});
}
render() {
const getData = (subpath = '') => fetch(`https://api.rawg.io/api/games${subpath}`)
.then(res => res.json())
.then(result => result.results);
console.log(getData)
}
I tried with axios but without success ...我试过 axios 但没有成功......
When I remove the comment, it shows me only the second fetch ...当我删除评论时,它只向我显示了第二次提取...
You need two separate fetch
calls for each API.每个 API 需要两个单独的
fetch
调用。 To wait for both to finish, use Promise.all
.要等待两者都完成,请使用
Promise.all
。
const getData = (subpath = '') => fetch(`https://api.rawg.io/api/games${subpath}`)
.then(res => res.json())
.then(result => result.results);
componentDidMount() {
Promise.all([
getData(),
getData('?page=2'),
])
.then(([dataSource1, dataSource2]) => {
this.setState({
isLoading: false,
isLoading2: false,
dataSource1,
dataSource2,
});
})
.catch((error) => {
// handle errors
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.