【问题标题】:React component props not getting rendered inside Next.js PageReact 组件道具未在 Next.js 页面中呈现
【发布时间】: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 中遗漏了一些为 SSR 获取数据的概念。

【问题讨论】:

    标签: javascript reactjs next.js jsx


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 2021-08-16
      • 2019-03-23
      • 2021-12-22
      • 1970-01-01
      • 2020-07-12
      相关资源
      最近更新 更多