使用 Next.js useRouter 拉标题道具不工作

Using Next.js useRouter to pull title props not working

正在尝试显示 index.js 文件中博客组件的标题道具。

点击任何一个链接时似乎都是空白。

index.js

import Layout from "../components/MyLayout";
import Link from "next/link";

const PostLink = props => (
  <li>
    <Link href="/p/[id]" as={`/p/${props.id}`}>
      <a>{props.id}</a>
    </Link>
  </li>
);

const Blog = () => {
  return (
    <Layout>
      <h1>My Blog</h1>
      <ul>
        <PostLink id="hello-nextjs" title="Hello Next.js" />
        <PostLink id="learn-nextjs" title="Learn Next.js" />
        <PostLink id="deploy-nextjs" title="Deploy Next.js" />
      </ul>
    </Layout>
  );
};

export default Blog;

这是 [id].js 文件中的 Post 组件。 {id} 正确显示:

import { useRouter } from "next/router";
import Layout from "../../components/MyLayout";

const Post = () => {
  const router = useRouter();
  const { id, title } = router.query;

  return (
    <Layout>
      <h1>{id}</h1>
      <p>Title: {title}</p>
      <p>This is the blog post content from [id].js</p>
    </Layout>
  );
};

export default Post;

NextJs Router doc开始,您还没有添加title进行查询,所以您需要将?title=${props.title}追加到Link

的href
import Layout from "../components/MyLayout";
import Link from "next/link";

const PostLink = props => (
  <li>
    <Link href={`/p/[id]?title=${props.title}`} as={`/p/${props.id}`}>
      <a>{props.id}</a>
    </Link>
  </li>
);

const Blog = () => {
  return (
    <Layout>
      <h1>My Blog</h1>
      <ul>
        <PostLink id="hello-nextjs" title="Hello Next.js" />
        <PostLink id="learn-nextjs" title="Learn Next.js" />
        <PostLink id="deploy-nextjs" title="Deploy Next.js" />
      </ul>
    </Layout>
  );
};

export default Blog;