通过query string传递数据

我们通过query string传递数据。 在我们的例子中,这是“title”查询参数。 我们的PostLink组件如下所示:

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

(检查’Link’组件的’href’ prop。)

就像这样,你可以通过query string传递任何你喜欢的数据。

创建 “post” 页

现在我们需要创建一个帖子来显示博客文章。 为了做到这一点,我们需要从query string中获取标题。 让我们看看如何做到这一点:

创建一个名为pages/post.js的文件并添加以下内容:

  1. import Layout from '../components/MyLayout.js'
  2. export default (props) => (
  3. <Layout>
  4. <h1>{props.url.query.title}</h1>
  5. <p>This is the blog post content.</p>
  6. </Layout>
  7. )

现在我们的页面将如下所示:

通过query string传递数据 - 图1

以上代码中发生了什么。

  • 每个页面都会得到一个名为“URL”的prop,其中有一些与当前URL相关的详细信息。
  • 在这种情况下,我们使用的是包含有query string参数的“query”对象。
  • 所以我们得到的标题是props.url.query.title

我们来简单的修改我们的应用程序。 将“pages/post.js”的内容替换为以下内容:

  1. import Layout from '../components/MyLayout.js'
  2. const Content = (props) => (
  3. <div>
  4. <h1>{props.url.query.title}</h1>
  5. <p>This is the blog post content.</p>
  6. </div>
  7. )
  8. export default () => (
  9. <Layout>
  10. <Content />
  11. </Layout>
  12. )

当您浏览此页面时会发生什么? http://localhost:3000/post?title=Hello%20Next.js

  1. ✦它将按预期工作。
  2. ✦没有任何东西。
  3. ✦它只会显示标题。
  4. ✓引发错误