NextJS
Before
I'm learning NextJS on the NextJS official website.There's a Chinese official website,but i'm reading the English version tutorial, so i write this article in English.
Pre-rendering 预渲染
NextJS可以预先生成页面相对较完整的 HTML 模版,然后在资源被请求时直接发送处理好的 HTML。而不是给一个空的 HTML 给客户端,客户端再识别到里面的 script 标签然后请求相关 JS 代码然后在浏览器端进行数据拼接然后渲染。
Pre-rendering Mode
NextJS提供两种预渲染模式。 Static Generation and Server-side Rendering。
Static Generation
Static Generation 静态生成是在项目构建时处理相关页面。 NextJS 提供 getStaticProps
异步函数,可以在该函数中处理页面在预渲染需要的数据并在函数中返回它。返回的数据将作为组件的属性 props
传递给组件。
const Home: FC = ({props}) => {
return <div>
{
props // do something
}
</div>
}
export default Home
export async function getStaticProps() {
// do something
return {
props: {}
}
}
Server-side Rendering
A quick graphical summary:
There is a method provided which called getServerSideProps
, and you need export it in the page.
Client Side Rendering
Client Side Rendering works well for user dashboard which data is frequently updated and SEO is not relevant.
NextJS provide a hook to handle client side request called SWR.
More detail in https://swr.vercel.app
Dynamic Routes
There's a lot you need to process by yourself. Lists the all routes that may be visit with url, then pass the different content by different route.
A quick graphical summary:
There are two asynchronous function need to export.
getStaticPaths
and getStaticProps
. This two function invokes only in server side, and it won't included in the JS bundle.
We need lists all the routes in getStaticPaths
and return it.
Then we can get the current route in getStaticPaths
's params.So we can pass the different props to component.