javascript - 遍历数组并动态发送http请求

标签 javascript reactjs

好的,我有这个数组 pokemonColor=['name1', 'name2', 'name3']。我怎样才能遍历这个数组并动态发送 http 请求,这样我就可以像下面这样更新状态?因为我正在尝试的这个不起作用,它创建了一个 JavaScript 对象,但是它们太多了......

这就是我想要的:

this.state.pokemon:[ 
    {name: name1, img: img1},
    {name: name2, img: img2},
    {name: name3, img: img3} 
]

这就是我正在尝试的方式:

componentDidUpdate() {
    // console.log(this.state.pokemonColor);
    this.state.pokemonColor.forEach(pok => {

      axios.get(`https://pokeapi.co/api/v2/pokemon/${pok}/`).then(res => {
        // console.log(res.data.sprites.front_shiny);


        this.setState({
          ...this.state,
          pokemon: {
            name: res.data.name,
            img: res.data.sprites.front_shiny
          }
        });
      });
    });
    // console.log(this.state.pokemon);
  }

最佳答案

首先 - this.state.pokemon = [...] 直接改变状态。您的应用可能会崩溃,或者至少您会在控制台中收到一条长长的红色错误。

其次 - 您不必在 setState 函数中解构 state

第三 - 对于每个 axios get 请求,您都在覆盖您所在州的 pokemon 字段。我建议您将 pokemons 保存在数组中。

this.setState((prevState) => ({
   pokemon: [
      ...prevState.pokemon,
      {
         name: res.data.name,
         img: res.data.sprites.front_shiny,
      },
   ],
});

然后您将能够通过引用 this.state.pokemons 来访问您的 pokemons,这将是一个对象数组。

关于javascript - 遍历数组并动态发送http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53571210/

相关文章:

javascript - 为什么 [1,2] + [3,4] = "1,23,4"在 JavaScript 中?

javascript - 相对位置偏移错误

reactjs - react native 接触返回未定义

javascript - 当分解成组件时,登录表单 React 不起作用

javascript - 如何在jqgrid的custom_func中显示自定义警告框

javascript - Leaflet.js geoJSON 中按大洲分组

javascript - 多个套接字覆盖自身

javascript - 使用 jQuery 和 Bootstrap 的 webpack 导入第三方库

javascript - 图片在 Chrome 选项卡上加载正常,但在 React 代码中返回 403

javascript - Bundle.js 无法识别我的文件之一?