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

Next.js中getStaticProps传递数据失败,news始终为undefined求助

Next.js getStaticProps 未执行导致news始终为undefined问题

我在用Next.js的getStaticProps时碰到了问题:组件接收的news始终是undefined,怀疑这个函数根本没执行。之前旧版本的Next.js能正常运行,升级到最新版本后就出现了这个问题。

我已经试过以下操作,但问题依旧:

  • 返回假数据替代MongoDB查询结果
  • 移除TypeScript改用纯JavaScript

getStaticProps 相关代码

type NewsItem = {
  id: string;
  published: string;
  author: string;
  avatar: string;
  title: string;
  background: string;
  subtitle: string;
  category: string;
};

export const getStaticProps: GetStaticProps<{
  news: NewsItem[];
}> = async () => {
  const client = await MongoClient.connect(`${process.env.REACT_MONGO_URL}`);
  const db = client.db();

  const newsCollection = db.collection("news");
  const news1 = await newsCollection.find().toArray();
  console.log("news2:", news1);
  client.close();

  return {
    props: {
      news: news1.map((nw) => ({
        published: nw.published,
        author: nw.author,
        avatar: nw.avatar,
        title: nw.title,
        background: nw.background,
        subtitle: nw.subtitle,
        category: nw.category,
        id: nw._id.toString(),
      })),
    },
  };
};

组件接收代码

const News = ({ news }: InferGetStaticPropsType<typeof getStaticProps>) => {
  console.log("news1", news);
...
export default News;

内容的提问来源于stack exchange,提问作者mrnja

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:54:55