1

我目前正在尝试使用 getStaticProps() 函数在我的 Next.js 项目中获取一些数据,但我继续收到此错误:

TypeError:无法读取未定义的属性“地图”

我的代码如下所示:

export const getStaticProps = async () => {
    const data = [
        {
            "id": 1,
            "question": "Lorem ipsum dolor sit amet consectetur adipisicing elit.",
            "answer": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Iste magni at magnam placeat. Non, saepe?"
        },
        {
            "id": 2,
            "question": "Lorem ipsum dolor sit amet consectetur adipisicing elit.",
            "answer": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Iste magni at magnam placeat. Non, saepe?"
        }
    ]
    return {
        props: {
            questions: data
        }
    }
}

export default function FAQ({ questions }) {
    return (
        <div className="p-8 grid bg-blanco" >
            <div className="grid place-content-center text-center mt-10 md:mt-0" >
                <h1 className="text-2xl text-gun-rose-700 font-bold" >¿Tiene preguntas? Mira aquí</h1>
                <h3 className="text-gun-rose-300 mt-4 max-w-2xl" >Lorem ipsum dolor sit amet consectetur adipisicing elit. Sunt, suscipit. Aliquid molestias eveniet ullam? Dolores, minus? Perspiciatis neque voluptates iste!</h3>
            </div>
            {questions.map(q => (
                <div className="" key={q.id}>
                    <h3 className="">{q.question}</h3>
                    <p className="">{q.answer}</p>
                </div>
            ))}
        </div>
    )
}

任何指导将不胜感激,在此先感谢:)

4

1 回答 1

0

这可能是一个异步问题,无法立即获得问题。尝试在问题开始时进行空检查。

export default function FAQ({ questions }) {
    return (
        <div className="p-8 grid bg-blanco" >
            <div className="grid place-content-center text-center mt-10 md:mt-0" >
                <h1 className="text-2xl text-gun-rose-700 font-bold" >¿Tiene preguntas? Mira aquí</h1>
                <h3 className="text-gun-rose-300 mt-4 max-w-2xl" >Lorem ipsum dolor sit amet consectetur adipisicing elit. Sunt, suscipit. Aliquid molestias eveniet ullam? Dolores, minus? Perspiciatis neque voluptates iste!</h3>
            </div>
            {questions && questions.map(q => (
                <div className="" key={q.id}>
                    <h3 className="">{q.question}</h3>
                    <p className="">{q.answer}</p>
                </div>
            ))}
        </div>
    )
}

编辑1:

如警告中所述,getStaticProps方法只能用于页面的顶级组件

解决方法是将getStaticProps方法移动到顶级页面组件。我已经在沙箱中演示了这个,因为文件夹结构非常重要,链接在这里

于 2021-09-28T09:04:31.463 回答