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

Next.js+TypeScript中getStaticProps使用问题:获取数据返回undefined

问题分析与解决

你的问题出在组件接收getStaticProps返回值的方式上:

  • getStaticProps返回的props会作为组件函数的第一个参数传入,而不是第二个参数。你现在把allPosts从第二个参数(组件上下文对象)里获取,所以打印出来是undefined。

修正后的代码

import { AppContext } from '@/helpers/Helpers'
import axios from 'axios'
import { GetStaticProps} from 'next'
import React, {useContext} from 'react'
import Tweet from './Tweet'
import { TweetsContainer } from './Tweets.styled'

// 定义正确的Props类型
export interface IAppProps {
  allPosts: any[] // 根据你的数据结构替换成具体类型
}

export default function Tweets(props: IAppProps) {
  // 从第一个参数props中解构allPosts
  const { allPosts } = props
  console.log(allPosts);
  
  return (
    <div>
        <TweetsContainer>
            <div>
            </div>
        </TweetsContainer>
    </div>
  );
}

export const getStaticProps: GetStaticProps<IAppProps> = async () => {
  const res = await axios.get(`http://localhost:7000/api/tweets`)
  const data = res.data
  
  return {
    props: { allPosts: data }   
  }
}

额外说明

  1. 用TypeScript时,建议给getStaticProps指定泛型IAppProps,这样能获得类型校验,避免传参错误。
  2. 尽量不要用any类型,根据后端返回的帖子数据结构,把IAppProps里的allPosts类型定义得更具体,比如allPosts: { id: string; content: string; ... }[]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 02:37:05