简体   繁体   English

nextjs getServerSideProps vs API

[英]nextjs getServerSideProps vs API

I'm trying to understand the main difference between getServerSideProps and just using useSWR inside of the page component.我试图了解 getServerSideProps 与仅在页面组件内部使用 useSWR 之间的主要区别。 If I run something like this inside getServerSideProps:如果我在 getServerSideProps 中运行这样的东西:

export const getServerSideProps = async () => {

  try {
    const palettes = []
    const docRef = query(collection(db, 'palettes'), orderBy('likes', 'desc'), limit(16))
    const docData = await getDocs(docRef)
    docData.forEach((doc) => {
      palettes.push(doc.data())
    })

    if (!docData) {
      return {
        props: {
          data: { error: 'Failed to load palettes. Please refresh the page.'}
        }
      }
    } else {
      return {
        props: {
          data: { palettes }
        }
      }
    }

  } catch (e) {
    console.log('error:', e)
  }
}

It will run at build time and then on each request by the user when viewing/navigating to the page?它会在构建时运行,然后在用户查看/导航到页面时的每个请求上运行?

Then what would be the difference from just using useSWR or another API fetcher like:那么与仅使用 useSWR 或另一个 API 提取器有什么区别,例如:

export default function PaletteSlugs({ slug }) {
  const { data, error } = useSWR(`/api/palette/${slug}`, fetcher)
  return (
   {data}
  )
}

Also could this affect how many request/reads will happen on the database?这也会影响数据库上将发生多少请求/读取?

Simply, using getServerSideProps will get the API data by the node.js server side, while the HTML page will be completely populated by the node.js server side, so if you try to open the source code of the browser you will see all data already exist in the source code, this will be better for SEO Simply, using getServerSideProps will get the API data by the node.js server side, while the HTML page will be completely populated by the node.js server side, so if you try to open the source code of the browser you will see all data already exist in the源代码,这对SEO会更好

But useSWR will get the data on the client-side like normal fetch and the data will be populated by the client side.但是useSWR将像正常fetch一样在client-side获取数据,并且数据将由客户端填充。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM