当控制台日志显示具有对象的数组时,React应用程序上的Promise挂起问题

new9mtju  于 2022-10-22  发布在  React
关注(0)|答案(1)|浏览(118)

我无法从https://thecatapi.com/加载图像。当我尝试控制台记录fetchCatImages中的响应时,我得到了一个数组。当我在App.js中控制台记录图像时,我得到了PromiseState: “fulfilled”PromiseResult: Array(5)的挂起承诺。有人能告诉我我在这里做错了什么吗?
编辑:所以我现在明白异步等待总是返回一个Promise。我通读了How do I return the response from an asynchronous call?,但仍不确定如何在App.js上显示数据。

import React from 'react';
import './App.css';

async function fetchCatImages() {
    let images = [];
    await fetch('https://api.thecatapi.com/v1/images/search?limit=5')
        .then((res) => res.json())
        .then((data) => (images = data))
        .catch((e) => {
            console.error('fetch failed!');
            console.error(e);
        });
    console.log('file: App.js ~ line 16 ~ fetchCatImages ~ images', images); 
    // logs show an Array with 5 objects

    return images;
}

function App() {
    const images = fetchCatImages();
    console.log('App.js ~ line 7 ~ App ~ images', images);
    // logs shows Promise {pending}, PromiseState: “fulfilled”, PromiseResult: Array(5) 

    return (
        <>
            {!images.length ? (
                <h3>There are no cats</h3>
            ) : (
                {images.map(({ id, url }) => (
                    <div key={id}>
                        <img src={url} height={50} width={50} />
                    </div>
                ))}
            )}
        </>
    );
}

export default App;

我还尝试使用try-catch而不使用异步等待,但仍然遇到同样的问题。

function fetchCatImages() {
    let images = [];

    try {
        images = fetch('https://api.thecatapi.com/v1/images/search?limit=5').then((res) => res.json());
    } catch (e) {
        console.error('fetch failed!');
        console.error(e);
    }

    return images;
}
6ss1mwsb

6ss1mwsb1#

尝试以下操作:

import React, { useState, useEffect } from "react";
import './App.css';

export default function App() {
  const [cats, setCats] = useState([]);

  useEffect(() => {
    const fetchCatImages = async () => {
      await fetch("https://api.thecatapi.com/v1/images/search?limit=5")
        .then((res) => res.json())
        .then((data) => setCats(data))
        .catch((e) => {
          console.error("fetch failed!");
          console.error(e);
        });
    };

    fetchCatImages().catch(console.error);
  }, []);

  return (
    <>
      {cats.length ? (
        cats.map(({ id, url }) => (
          <div key={id}>
            <img src={url} height={50} width={50} />
          </div>
        ))
      ) : (
        <h3> There are no cats </h3>
      )}
    </>
  );
}

相关问题