1.nextjs服务端请求,静态渲染
const Category = () => { return <div> </div>;}export async function getServerSideProps() { // Fetch data from external API const res = await fetch('https://...'); const categoryList = await res.json(); // Pass data to the page via props return { props: { categoryList } };}export default Category;
或带参数渲染获取数据。
const DemoPage = (props) => { const { serverData } = props; return <div> </div>;}export async function getServerSideProps(context: { query: { id: any };}) { // Fetch data from external API const res = await fetch( `https://.../page/${context.query.id}`, ); const serverData = await res.json(); // Pass data to the page via props return { props: { serverData } };}export default DemoPage;
2.更改url, “http://.../page?id=1“ 变换 ”http://.../page/1“ ;
在page目录下的页面创建[id].tsx文件,页面内容相同。
使用 Link 链接跳转, as转译路径;
import Link from 'next/link'; <Link href={`/page?id=${data.id}`} as={`/page/${data.id}`}> <a>只允许一个子元素,不能同时包含两个元素</a> </Link>
最后你就可以通过 /page/1 来访问页面了,查看网页源代码可以看到数据,这样有利于搜索引擎搜索到本网站。还有可以给a标签加rel="关键字",img加alt="关键字"等。或者给页面head加title标签。例如:
import Head from 'next/head';<Head> <meta name="baidu-site-verification" content="code-Vw6MQwYwzw" /> <meta name="Description" content="网站关键内容" /> <meta name="keywords" content="网站关键字" /> <title> 网站标题关键字 </title> <link rel="icon" href="/favicon.ico" /> </Head>