【问题标题】:getStaticProps returns empty props objectgetStaticProps 返回空的 props 对象
【发布时间】:2021-05-13 08:29:49
【问题描述】:

我正在尝试使用 getStaticProps (Next.js) 呈现登录页面,但它的行为与预期不符。这是我的组件:

import { GetStaticProps } from 'next'

const Brief = (props) => {

    console.log(JSON.stringify(props)) // returns an empty object
    return (
        <>
            {props[0]}
            {props[1]}
            {props[2]}
        </>
    )
}

export const getStaticProps: GetStaticProps = async (context) => {
    const WhatIUse = <div className="WhatIUse">What I use</div>

    const introduction = <div className="introduction">Introduction</div>

    const ContactInfo = <div className="ContactInfo">Where to find me</div>

    return {
        props: [introduction, WhatIUse, ContactInfo]
    }
}

export default Brief

日志语句显示props 作为空对象返回,可能是什么问题?

【问题讨论】:

  • 当你尝试运行它时肯定会出错?
  • 完全没有,我正在运行生产版本,控制台中没有错误消息,只是元素没有显示。
  • 您应该运行开发版本以确保您看到所有错误。

标签: typescript next.js


【解决方案1】:

确保您实际上是在页面文件上使用该功能,(“页面”文件夹内的文件)

我遇到了同样的问题,但是我在组件中使用了该函数,导致一个空对象

当我开始在页面文件中使用它时,该函数的行为符合预期

【讨论】:

【解决方案2】:

这种方法有几个问题。

首先,getStaticProps 中返回的变量 props 必须是一个 object,其中包含可序列化为 JSON 的值。您正在尝试传递一个包含 JSX 元素(不可序列化)的 array

其次,getStaticProps 用于获取数据进行预渲染,你不是要在那里生成 JSX,这将在组件本身中完成。

这是一个基于您的初始代码的实际示例:

const Brief = (props) => {
    console.log(props) // Will log props passed in `getStaticProps`

    return (
        <>
            <div className="WhatIUse">{props.data[0]}</div>
            <div className="introduction">{props.data[1]}</div>
            <div className="ContactInfo">{props.data[2]}</div>
        </>
    )
}

export const getStaticProps: GetStaticProps = async (context) => {
    const WhatIUse = 'What I use'
    const introduction = 'Introduction'
    const ContactInfo = 'Where to find me'

    return {
        props: {
            data: [introduction, WhatIUse, ContactInfo]
        }
    }
}

export default Brief

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-31
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    • 2015-02-11
    • 2020-12-21
    • 2019-04-08
    相关资源
    最近更新 更多