async function fetchData() { const res = await fetch('/api/data'); // 发送 GET 请求到 '/api/data' const data = await res.json(); // 将响应转换为 JSON 格式 return data; // 返回获取到的数据 } 在页面组件的 getServerSideProps 方法中调用上述定义的异步函数...
Good to know:It's still possible to fetch data client-side. We recommend using a third-party library such asSWRorReact Querywith Client Components. In the future, it'll also be possible to fetch data in Client Components using React'suse()hook. 很高兴知道:仍然可以在客户端获取数据。我们建...
Server-side Rendering (SSR) Client-side Rendering 客户端渲染其实就是我们经常看到的前后端分离的场景了:只提供一个 html,拿到的 JS 再去渲染页面。 importuseSWRfrom'swr'functionProfile(){const{data,error}=useSWR('/api/user',fetch)if(error)returnfailed to loadif(!data)returnloading...returnhello{da...
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重新构建页面。 复制 exportdefaultfunctionHome({data}) {return(// Use data); }exportasyncfunctiongetServerSideProps() {// Fetch data from external apiconstres=awaitfetch('https://.../data')constdata=awaitres.json()// Will be passed to the page component...
constshouldFetchData=routeInfo.__N_SSG||routeInfo.__N_SSP;if(shouldFetchData){const{json,cacheKey:_cacheKey}=data?.json?data:awaitfetchNextData({dataHref:this.pageLoader.getDataHref({href:formatWithValidation({pathname,query}),asPath:resolvedAs,locale}),isServerRender:this.isSsr,parseJSON:true...
exportasyncfunctiongetServerSideProps(){ constres =awaitfetch(`https://app-url/data`) constdata =awaitres.json() return{props:{data}} } 这些数据在每次请求时被获取,并通过props传递给新闻组件。 代码拆分 代码拆分是将代码分成几块,让浏览器可以按需加载。它减少了初始加载时发送到浏览器的代码量,因为...
接下来,定义getServerSideProps函数并使用它来获取构建站点地图所需的数据。在此示例中,我们将向 发出 HTTP 请求以EXTERNAL_API_URL检索博客文章列表:export async function getServerSideProps({ res }) { // Fetch the data from the API const response = await axios.get(EXTERNAL_API_URL);const posts ...
}//This gets called on every requestexport const getServerSideProps = async () =>{//Fetch data from external API//const res = await fetch(`https://.../data`)//const data = await res.json()//这里不测试外部数据接口,直接使用测试数据const data = { message: 'Test message'}//显示在服...
const res = await fetch(`https://jsonplaceholder.typicode.com/todos`) const data = await res.json() return { props: { data } } } 使用SSR,你需要导出一个名为getServerSideProps的 async 函数。这个函数会在每次请求的时候被调用。返回的数据会通过组件的 props 属性传递给组件。