You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js无法从外部API获取并展示猫事实的问题求助

问题修复方案

错误点1:函数名拼写错误

你写的getSataticProps存在拼写错误,正确的静态数据获取函数名是getStaticProps(少写了一个字母t)。这个错误会导致Next.js无法识别该函数,数据根本无法传递到页面组件中。

错误点2:错误使用数组遍历方法

调用https://catfact.ninja/fact接口返回的是单个对象(结构为{ fact: "猫咪趣味内容", length: 内容长度 }),并不是数组,因此不能用map方法遍历。直接访问home.fact就能获取到对应的趣味事实。

修复后的完整代码

import Head from 'next/head';
import styles from '../styles/Home.module.css';

export const getStaticProps = async () => {
  const res = await fetch('https://catfact.ninja/fact');
  const data = await res.json();

  return {
    props: { home: data },
  };
};

const Home = ({ home }) => {
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <h1 className={styles.title}>Let's see fun facts about cats</h1>
        {home && <p>{home.fact}</p>}
      </main>
    </div>
  );
};
export default Home;

额外补充

  • 使用home && ...做存在性判断,能避免数据未加载完成时出现报错
  • 如果需要获取多条猫咪趣味事实,可以调用接口https://catfact.ninja/facts,该接口返回数组格式数据,此时再用map遍历就合理了

内容的提问来源于stack exchange,提问作者Yuri Oliveira Gochi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 01:31:00