getStaticProps 返回空的道具对象

时间:2021-02-09 17:02:15

标签: typescript next.js getstaticprops

我正在尝试使用 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”作为空对象返回,可能是什么问题?

1 个答案:

答案 0 :(得分:0)

这种方法有一些问题。

首先,props 中返回的变量 getStaticProps 必须是一个 对象,其中包含可序列化为 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