【发布时间】:2021-09-04 02:38:46
【问题描述】:
我正在使用 Next.js 制作一个小型 Web 应用程序,但我不知道为什么,但是当我使用该组件时,getServerSideProps() 没有运行。我之前在/pages 的一个页面上有以下代码,但我将它移动到用作组件。
export const getServerSideProps = async () => {
console.log("in getServerSideProps") // never shows
let bans = await fetch('http://localhost:3000/api/get_bans').then((res) => {
return res.json();
})
return {
props: { bans: bans }
}
}
const BansList = (listName, bans) => {
bans = bans.bans
console.log(bans) // undefined
return (
<h1>test</h1>
)
}
我已经精简了代码,以便轻松显示问题所在。当我将其用作组件时,getServerSideProps 未运行,因此 bans 始终未定义。
【问题讨论】:
-
我不确定,但我相信
getServerSideProps仅适用于 pages 文件夹下的 Components。 -
你在
BansList组件中没有正确访问props,应该是:const BansList = ({ listName, bans })。