【问题标题】:getServerSideProps always return null object as propsgetServerSideProps 总是返回 null 对象作为道具
【发布时间】:2022-08-04 17:30:00
【问题描述】:

当我尝试下面的代码时,我在控制台中得到空对象或未定义。

import React from \'react\'
function Main({ data }) {
    console.log(data);
    return (
        <div></div>
    )
}
export async function getServerSideProps() {
    const res = await fetch(`https://api.unsplash.com/search/photos?query=super&client_id=QqHDWLqMPbUQMFYXaMOjLF9iT81ceZzfXkMkiJF1hTQ`)
    const data = await res.json()
    return { props: { data } }
}
export default Main

有什么错误吗? 我也尝试在 Main 函数中返回一些东西,但仍然未定义。

  • 您在下一页或组件中使用getServerSideProps 吗?
  • 我在组件文件夹中制作 Main.js 并在里面使用 getServerSideProps
  • 组件不能使用getServerSideProps,只有页面有这种能力。如果将其移至 pages 文件夹,它应该可以按预期工作。

标签: reactjs next.js server-side-rendering


【解决方案1】:

关注docs

getServerSideProps 只能从.您不能从非页面文件中导出它。

您不能在组件中使用getServerSideProps。所以让你的Main.js 成为pages

// pages/main.js
function Main({ data }) {
  return <div>Main</div>
}

export async function getServerSideProps() {
    const res = await fetch(`https://api.unsplash.com/search/photos?query=super&client_id=QqHDWLqMPbUQMFYXaMOjLF9iT81ceZzfXkMkiJF1hTQ`)
    const data = await res.json()
    return { props: { data } }
}
export default Main

仅当您需要预渲染必须在请求时获取数据的页面时才应使用getServerSideProps

或将Main.js 保留为组件并使用useEffect 保留fetch data on client

function Main({ data }) {
  const [data, setData] = useState(null)
  const [isLoading, setLoading] = useState(false)

  useEffect(() => {
    setLoading(true)
    fetch('https://api.unsplash.com/search/photos?query=super&client_id=QqHDWLqMPbUQMFYXaMOjLF9iT81ceZzfXkMkiJF1hTQ')
      .then((res) => res.json())
      .then((data) => {
        setData(data)
        setLoading(false)
      })
  }, [])

  if (isLoading) return <p>Loading...</p>
  if (!data) return <p>No profile data</p>

  return (
    <div>// rest of you code</div>
  )
}

【讨论】:

  • 我将 Main.js 文件移动到 pages 文件夹中,并将 Main.js 调用到 index.js 中,但它仍然显示未定义。有什么问题吗?
  • @Krunal 可以说出原因^^。我试过了,你可以在这里查看working exammple
【解决方案2】:

你必须在页面目录中使用你的组件 serversideprops not support outside

【讨论】:

  • 这样做后它将起作用
猜你喜欢
  • 2015-09-16
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多