NextJS动态标题

NextJS dynamic title

一直在谷歌搜索,找到了改变 <title> 的方法。那个方式是这样的:https://github.com/zeit/next.js/tree/master/examples/layout-component

主要问题是,每次有人刷新 site/change 页面时,标题都会从 http://localhost:3000 变为实际标题(例如,关于我们),我有点担心如何这会影响 SEO。

动态更改页面标题的正确方法是什么?

我的布局文件:

import Link from 'next/link'
import Head from './../node_modules/next/head'

export default function Layout({ children, title = 'Welcome to my website' }) {
  return (
    <div>
        <Head>
          <title>{title}</title>
        </Head>

        {children}
    </div>
  )
}

查看 next-seo 并将其安装到您的 next.js 应用程序中。

yarn add next-seo 
# or 
npm install --save next-seo

它会神奇地为您处理页面标题和元描述。

import React from 'react';
import { NextSeo } from 'next-seo'; // then add the `NextSeo` at any `pages/` that you wish

export default () => (
  <>
    <NextSeo
      title="About Us, or just any title that you wish"
      description="Then with a short description here."
    />
    <p>Simple Usage</p>
  </>
);

我在这里 web app 自己实施了相同的策略。

我在依赖项中重新安装了 "next" 和 "next-routes",现在可以使用了。

如果您需要动态 title/description,例如对于路由参数的情况,您可以这样做。 (假设页面名称是[id].js)

import React from 'react'
import { NextSeo } from 'next-seo' //as proposed by @xun
// import Head from "next/head" //alternative solution

const Detail = ({id}) => {
  
  const title = `My ${id} title.`
  const description = `My ${id} description.`
  
  return (
     <>
     <NextSeo
      title={title}
      description={description}
    />
    <p>It works!</p>
    </>
    )}

export default Detail

在您的文件末尾:

export async function getServerSideProps({query}) {
  const { id } = query

  return {
    props: {
      id
    },
  };
}

祝你好运!

对我来说这行得通,

从下一个导入,

import Head from 'next/head'

并且在return声明中,

<>
    <Head>
      <title>Page Title</title>
    </Head>
    <section>
        <Your_JSX_CODE>
    </section>
  </>