React 组件道具未在 Next.js 页面中呈现

Posted

技术标签:

【中文标题】React 组件道具未在 Next.js 页面中呈现【英文标题】:React component props not getting rendered inside Next.js Page 【发布时间】:2021-05-05 01:15:00 【问题描述】:

我正在尝试在React 功能组件中呈现来自props 的数据,如下所示:

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 中遗漏了一些为 s-s-r 获取数据的概念。

【问题讨论】:

【参考方案1】:

我猜问题是 .map() 没有在您的代码中返回任何内容:

props.tags.map(tag => 
       tag.tagId 
       tag.tagName 
   )

您应该尝试以下方法:


   props.tags.map(tag => (
     <>
         tag.tagId 
         tag.tagName 
      </>
   ))

你也可以在props.tags &amp;&amp; props.tags.map()之前检查null

【讨论】:

以上是关于React 组件道具未在 Next.js 页面中呈现的主要内容,如果未能解决你的问题,请参考以下文章