【问题标题】:Cannot show images after fetching from an API从 API 获取后无法显示图像
【发布时间】:2020-10-10 22:58:51
【问题描述】:

我正在尝试使用 axios 链接两个获取请求。我的代码是:

const fetchCatsData = async  () => {
  
  const fetchBreeds = await axios.get("https://api.thecatapi.com/v1/breeds", {
    headers: {
      "x-api-key": "MY API KEY ",
    },
  })
  await fetchBreeds.data.map(breed => {
    axios.get(`https://api.thecatapi.com/v1/images/search?breed_ids=${breed.id}&include_breeds=false`)
    .then(res => breed.image_url = res.data[0].url)
  })
 
  dispatch({ type: FETCH_BREEDS, payload:  fetchBreeds.data })

它成功了,在反应开发工具中,我在我的上下文中看到一个名为“image_url”的特殊键,带有图像的 url。我点击它的值并打开请求的图像。

但是当我试图在图像 HTML 标记中显示图像时,它什么也没显示...

我错过了什么吗?

提前致谢

【问题讨论】:

    标签: reactjs request axios fetch chain


    【解决方案1】:

    从这里的代码中,我猜您正试图等到为 fetchBreeds.data 中的所有项目设置 image_url。但它不会那样工作。

    await fetchBreeds.data.map(breed => {
        axios.get(`https://api.thecatapi.com/v1/images/search?breed_ids=${breed.id}&include_breeds=false`)
        .then(res => breed.image_url = res.data[0].url)
      })
    

    您在地图功能上使用await。 map 函数不是异步的,因此当您调度操作时,尚未设置 image_urls。当您检查商店并发现 image_url 存在时,是因为 fetchBreeds.data 直接被 axios 调用突变,而没有使用 redux 调度系统。这并没有触发 UI 重新渲染,因此没有显示图像。发生的事情如下图所示:

    1. dispatch({ type: FETCH_BREEDS, payload: fetchBreeds.data }) 这首先发生。
    2. 通知组件重新渲染。 image_url 还没有设置,所以图片是空的
    3. .then(res => breed.image_url = res.data[0].url) 接下来调用这个。因为该函数持有fetchBreeds.data的引用,所以它直接改变了fetchBreeds.data对象,而不使用reducer。
    4. UI 未收到通知,因此它不知道 image_url 已更改且不会重新渲染。

    我建议你把函数改成:

      await Promise.All(fetchBreeds.data.map(breed => {
        return axios.get(`https://api.thecatapi.com/v1/images/search?breed_ids=${breed.id}&include_breeds=false`)
        .then(res => breed.image_url = res.data[0].url)
      }))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2019-04-25
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      相关资源
      最近更新 更多