所以我正在一个需要出于SEO目的而需要服务器端呈现的项目中,我在我的项目中使用了带有响应的Next JS。
我正在此链接https://nextjs.org/learn/basics/clean-urls-with-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
加载页面时,我在Chrome上签入了“查看源代码”,以检查它是否在服务器端呈现,但代码中没有包含“奶酪”的内容
我做错了吗?还是代码呈现在客户端?任何答案将不胜感激
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,否则它将在客户端生成。