![](/img/trans.png)
[英]Next.js: fetching data in getInitialProps(): server-side vs client-side
[英]Are dynamic routes in Next.js rendered server-side or client-side?
我正在一個項目中工作,該項目需要出於 SEO 目的進行服務器端渲染,並且我正在使用 Next.js 和 React,並且我正在使用Next.js 動態路由。
我創建了一個簡單的頁面來檢查它是否正常工作:
import Head from 'next/head'
import React, { Fragment } from 'react'
import { withRouter } from 'next/router'
class Product extends React.Component {
render() {
return (
<Fragment>
<Head />
<h1>{this.props.router.query.name}</h1>
</Fragment>
)
}
}
export default withRouter(Product)
我將代碼放在/pages/product/[name].js
中,運行開發服務器並訪問localhost:3000/product/cheese
。
頁面加載后,我在瀏覽器中檢查了頁面源以檢查它是否在服務器端呈現,並且代碼中沒有任何內容包含單詞cheese
。
我做錯了嗎? 它是在客戶端呈現的嗎?
import Layout from '../components/MyLayout';
import Link from 'next/link';
import fetch from 'isomorphic-unfetch';
const Index = props => (
<Layout>
<h1>Batman TV Shows</h1>
<ul>
{props.shows.map(show => (
<li key={show.id}>
<Link href="/p/[id]" as={`/p/${show.id}`}>
<a>{show.name}</a>
</Link>
</li>
))}
</ul>
</Layout>
);
Index.getInitialProps = async function() {
const res = await fetch('https://api.tvmaze.com/search/shows?q=batman');
const data = await res.json();
console.log(`Show data fetched. Count: ${data.length}`);
return {
shows: data.map(entry => entry.show)
};
};
正如您將很快看到的,您需要使用 getInitialProps 才能將其呈現在服務器端。 然后此頁面將在構建期間創建,並將在視圖源中包含所有適用的信息。 也會有 SEO。
當你運行 npm build 時,它會告訴你哪個是靜態生成的,什么是 ssr。 但是您需要使用 getInitialProps 否則它將在客戶端生成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.