Route Masking(路由定制)

在这里,我们将使用称为Route Masking的Next.js的独特功能。 基本上,它会在浏览器上显示与您的应用程序看到的实际URL不同的URL。

我们在我们的博客文章URL中添加一个路由掩码。

pages/index.js应用以下代码:

  1. import Layout from '../components/MyLayout.js'
  2. import Link from 'next/link'
  3. const PostLink = (props) => (
  4. <li>
  5. <Link as={`/p/${props.id}`} href={`/post?title=${props.title}`}>
  6. <a>{props.title}</a>
  7. </Link>
  8. </li>
  9. )
  10. export default () => (
  11. <Layout>
  12. <h1>My Blog</h1>
  13. <ul>
  14. <PostLink id="hello-nextjs" title="Hello Next.js"/>
  15. <PostLink id="learn-nextjs" title="Learn Next.js is awesome"/>
  16. <PostLink id="deploy-nextjs" title="Deploy apps with Zeit"/>
  17. </ul>
  18. </Layout>
  19. )

看看下面的代码块:

  1. const PostLink = (props) => (
  2. <li>
  3. <Link as={`/p/${props.id}`} href={`/post?title=${props.title}`}>
  4. <a>{props.title}</a>
  5. </Link>
  6. </li>
  7. )

<Link>元素中,我们使用了另一个称为“as”的支柱。 这是我们需要在浏览器上显示的URL。 您的应用看到的URL在“href” prop 中被提及。

现在尝试点击第一个博文,你将被导航到博客文章。

之后,点击返回按钮,然后按前进按钮。 会发生什么?

  1. It throws an error.
  2. It goes back to the index page and navigates again to the post page.
  3. It goes back to the index page but nothing happens after that.
  4. It goes back to the index page then throws an error.