簡體   English   中英

nextjs getServerSideProps vs API

[英]nextjs getServerSideProps vs API

我試圖了解 getServerSideProps 與僅在頁面組件內部使用 useSWR 之間的主要區別。 如果我在 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)
  }
}

它會在構建時運行,然后在用戶查看/導航到頁面時的每個請求上運行?

那么與僅使用 useSWR 或另一個 API 提取器有什么區別,例如:

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

這也會影響數據庫上將發生多少請求/讀取?

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會更好

但是useSWR將像正常fetch一樣在client-side獲取數據,並且數據將由客戶端填充。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM