gpt4 book ai didi

next.js - 您应该如何使用 getServerSideProps 在路由转换时获取客户端数据?

转载 作者:行者123 更新时间:2023-12-03 23:07:58 27 4
gpt4 key购买 nike

Next.js 9.3 引入 getServerSideProps .在 getInitialProps documentation它现在说:

If you're using Next.js 9.3 or newer, we recommend that you use getStaticProps or getServerSideProps instead of getInitialProps.



事情是: getInitialProps不只是在服务器端提供 Prop 。它还在客户端上运行并在路由转换时提供 Prop 。在初始服务器渲染后,如果路由发生变化, getInitialProps在客户端运行。那么,9.3 中引入的新方法如何解释这个非常基本的用例呢?

最佳答案

getServerSideProps

getServerSideProps only runs on server-side and never runs on the browser. If a page uses getServerSideProps , then:

When you request this page directly, getServerSideProps runs at the request time, and this page will be pre-rendered with the returned props.

When you request this page on client-side page transitions through next/link (documentation) or next/router (documentation), Next.js sends an API request to the server, which runs getServerSideProps. It’ll return JSON that contains the result of running getServerSideProps, and the JSON will be used to render the page.

All this work will be handled automatically by Next.js, so you don’t need to do anything extra as long as you have getServerSideProps defined.


对于 more info . getStaticProps

Only runs at build time

When a page with getStaticProps is pre-rendered at build time, in addition to the page HTML file, Next.js generates a JSON file holding the result of running getStaticProps.

This JSON file will be used in client-side routing through next/link (documentation) or next/router (documentation). When you navigate to a page that’s pre-rendered using getStaticProps, Next.js fetches this JSON file (pre-computed at build time) and uses it as the props for the page component. This means that client-side page transitions will not call getStaticProps as only the exported JSON is used.


对于 more info

关于next.js - 您应该如何使用 getServerSideProps 在路由转换时获取客户端数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61044867/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com