async function fetchData() { const res = await fetch('/api/data'); // 发送 GET 请求到 '/api/data' const data = await res.json(); // 将响应转换为 JSON 格式 return data; // 返回获取到的数据 } 在页面组件的getServerSideProps方法中调用
SSR - Server-Side Rendering, will run a special function to fetch data from API every page request on the server-side (before the page is loaded, that special function will run first, creating a delay, then after that, it will serve the page). SSG - Static Site Generation, will run ...
exportdefault({ data }) =>{//Render data ...}//This gets called on every requestexport const getServerSideProps = async () =>{//Fetch data from external APIconst res = await fetch(`https://.../data`)const data =await res.json()//Pass data to the page via propsreturn{ props: ...
为了确保页面在数据获取失败时不会崩溃,可以在getServerSideProps中添加错误处理: export async function getServerSideProps() { try { const response = await fetch('https://jsonplaceholder.typicode.com/posts'); if (!response.ok) { throw new Error('Failed to fetch data'); } const data = await r...
Client-side Rendering (CSR) Static Generation (SSG) Server-side Rendering (SSR) Client-side Rendering 客户端渲染其实就是我们经常看到的前后端分离的场景了:只提供一个 html,拿到的 JS 再去渲染页面。 importuseSWRfrom'swr'functionProfile(){const{data,error}=useSWR('/api/user',fetch)if(error)return...
每当用户请求时,使用getServerSideProps重新构建页面。 复制 exportdefaultfunctionHome({data}) {return(// Use data); }exportasyncfunctiongetServerSideProps() {// Fetch data from external apiconstres=awaitfetch('https://.../data')constdata=awaitres.json()// Will be passed to the page component...
请求记忆化 (Request Memoization):在单次服务器端渲染过程中,通过缓存具有相同 URL 和选项的 fetch 请求,优化数据获取。 数据缓存 (Data Cache):持久化 fetch 请求的结果,使其能够跨越多个服务器请求乃至多次部署,充当服务器端的数据存储。 全路由缓存 (Full Route Cache):在服务器端缓存静态渲染或经过重新验证的...
getServerSideProps 是Next.js 提供的用于服务端获取数据并将数据作为属性传递给页面组件的方法。你可以在该方法中调用 API,获取数据并返回给组件。例如: 代码语言:txt 复制 export async function getServerSideProps() { // 调用 API 获取返回值 const data = await fetch('/api/data'); const re...
const res = await fetch(`https://jsonplaceholder.typicode.com/todos`) const data = await res.json() return { props: { data } } } 使用SSR,你需要导出一个名为getServerSideProps的 async 函数。这个函数会在每次请求的时候被调用。返回的数据会通过组件的 props 属性传递给组件。
根据 getServerSideProps 的调用时机,我们可以知道这个方法适用于展示需要经常更新的数据。下面放个官方例子:exportdefaultfunctionPage({ data }) {// 渲染数据...}// 这个方法每次请求时都会调用exportasyncfunctiongetServerSideProps() {// 从外部 API 获取数据const res = await fetch(`https://.../data`...