Next.js 中的动态路由是在服务器端还是在客户端呈现?
Are dynamic routes in Next.js rendered server-side or client-side?
我在一个项目中工作,该项目需要为 SEO 目的进行服务器端渲染,我正在使用 Next.js 和 React,并且我正在使用 Next.js dynamic routing.
我创建了一个简单的页面来检查它是否正常工作:
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 否则它会在客户端生成。
我在一个项目中工作,该项目需要为 SEO 目的进行服务器端渲染,我正在使用 Next.js 和 React,并且我正在使用 Next.js dynamic routing.
我创建了一个简单的页面来检查它是否正常工作:
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 否则它会在客户端生成。