我正在尝试理解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}
)
}此外,这是否会影响数据库上会发生多少次请求/读取?
发布于 2022-08-16 20:03:22
简单地说,使用getServerSideProps将在Node.js服务器上获取Node.js数据,而HTML将被服务器上的Node.js完全填充。如果您尝试打开浏览器中的页面源,您将看到页面源中已经存在所有数据,这将对SEO更好。
但是useSWR会像普通fetch一样在客户端获取数据,数据将在客户端填充。
https://stackoverflow.com/questions/73379639
复制相似问题