Next.js项目中输出对象数据失败:h1标题显示为空
解决Next.js页面h1标题为空的问题
问题出在getServerSideProps的使用规则上:Next.js的数据获取方法(包括getServerSideProps)仅对默认导出的页面组件生效,你当前用的是命名导出export const PopularPosts,导致getServerSideProps返回的props无法传递到组件中,所以props.content为空,h1自然显示空白。
修正方案
方案一:改为默认导出组件
直接把组件改成默认导出形式:
import styles from './PopularPosts.module.scss' export async function getServerSideProps() { return { props: { content: "Some content" } } } export default function PopularPosts(props) { return ( <> <h1>{props.content}</h1> </> ) }
方案二:保留命名导出,追加默认导出
如果需要保留命名导出,在文件末尾增加默认导出语句:
import styles from './PopularPosts.module.scss' export async function getServerSideProps() { return { props: { content: "Some content" } } } export const PopularPosts = (props) => { return ( <> <h1>{props.content}</h1> </> ) } // 追加默认导出,让getServerSideProps能关联到组件 export default PopularPosts;
完成以上修改后,getServerSideProps返回的content就能正常传递到组件中,h1会显示"Some content"。
内容的提问来源于stack exchange,提问作者Illia Skoropad
相关产品推荐
相关产品推荐

