Next.js 响应数据丢失

问题描述 投票:0回答:1

我真的不知道我的代码到底出了什么问题,它没有显示在我的网站上获取的数据。当我使用

console.log(data)
时,它会毫无问题地获取数据,但是当我写
src={data.img1}
时,它不会显示任何内容。

 async function getData() {
  const res = await fetch("http://localhost:3000/api/games");

  if (!res.ok) {
    throw new Error("Failed to fetch data");
  }

  return res.json();
}

const Games = async () => {
  const data = await getData();
  console.log(data);
  return (
    <div className={styles.container}>
      <div className={styles.container}>
        <Image src={data.img1} alt="..." width={500} height={500} />
      </div>
    </div>
  );
};

export default Games;

如何查看返回的数据?

reactjs api next.js fetch fetch-api
1个回答
0
投票

这不是处理 API 调用并根据 API 数据返回 JSX 的正确方法。

您需要使用

useEffect
钩子在挂载时调用 API,并使用
useState
钩子将数据存储在状态中。

下面是相同的实现

const [data, setData] = useState(null);

const getData = async () => {
  const res = await fetch("http://localhost:3000/api/games");
  if (!res.ok) {
    throw new Error("Failed to fetch data");
  } else {
    const games = res.json();
    setData(games);
  }
};

useEffect(() => {
  getData();
}, []);

return (
  <div className={styles.container}>
    <div className={styles.container}>
      <Image src={data?.img1} alt="..." width={500} height={500} />
    </div>
  </div>
);
© www.soinside.com 2019 - 2024. All rights reserved.