gpt4 book ai didi

reactjs - 在循环中使用 axios 发出多个 get 请求的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-03 13:37:40 30 4
gpt4 key购买 nike

我在循环中发出多个请求时遇到问题。

我正在制作一个 react 应用程序,它呈现多个称为卡片的组件。在每张卡片中我想提出一些请求,所以我得到了这个。

componentWillMount(){
if(this.props.movies){
let promises = []
this.props.movies.forEach((item, i) => {
console.log(item)
let movieUrl = `http://localhost:3000/movies/${item}`
promises.push(axios.get(movieUrl))
})

axios.all(promises).then(res => console.log(res))
}
}

Movies 是我从父组件获取的数组。所以显然是有效的,因为我得到了结果,但tit总是与最后一张卡的最后一个元素有关。这是一张图片:

Look, Even the item is changing (those tt....) I always get the last responde, what can I do ?

最佳答案

当您确实需要映射并使用item.imdbID而不是item<构建URL时,应该避免使用forEach/

componentWillMount(){
if(this.props.movies){
const promises = this.props.movies.map(item => {
const movieUrl = `http://localhost:3000/movies/${item.imdbID}`
console.log(movieUrl)
return axios.get(movieUrl)
)
Promise.all(promises).then(results => console.log(results))
}
}

编辑1:由于不兼容的构建配置而删除了异步/等待Edit2:使用 item.imdbID 而不是 item 和记录的网址

关于reactjs - 在循环中使用 axios 发出多个 get 请求的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52235331/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com