我试图从props
中呈现React
功能组件的数据,看起来像这样:
interface TagsComponentProps {
tags: Tag[];
}
const TagsComponent: FC<TagsComponentProps> = (props: TagsComponentProps) => (
<>
{props.tags.length === 0 &&
<LoadingStateComponent />
}
{props.tags.map(tag => {
{ tag.tagId }
{ tag.tagName }
})
}
</>
)
export default TagsComponent;
在Next.js
页面内,getStaticProps
方法内接收数据。它看起来像这样:
const IndexPage = ({ tags }: InferGetStaticPropsType<typeof getStaticProps>) => (
<>
<LayoutComponent>
<TagsComponent tags={tags} />
</LayoutComponent>
</>
)
export default IndexPage;
export const getStaticProps = async () => {
const res = await fetch(`${process.env.HOST}/api/tags/read`)
const data = await res.json()
// if (error) {
// return <ErrorComponent errorMessage={'Ошибка загрузки тегов'} />
// }
return {
props: {
tags: data.Items as Tag[]
}
}
}
但是没有任何东西被渲染,尽管我正在接收数据。可能我遗漏了Next.js
中SSR数据获取的一些概念。
我猜问题是.map()
在你的代码中没有返回任何东西:
{props.tags.map(tag => {
{ tag.tagId }
{ tag.tagName }
})
}
相反,您应该尝试如下操作:
{
props.tags.map(tag => (
<>
{ tag.tagId }
{ tag.tagName }
</>
))
}
也可以在props.tags && props.tags.map()
之前做null
检查。