实现 Post 页面

现在让我们尝试实现“/ post”页面,其中显示有关电视节目的详细信息。

首先,打开server.js并更改/p/:id路由,其中包含以下内容:

  1. server.get('/p/:id', (req, res) => {
  2. const actualPage = '/post'
  3. const queryParams = { id: req.params.id }
  4. app.render(req, res, actualPage, queryParams)
  5. })

然后重新启动您的应用程序以应用上述代码更改。

以前,我们将title查询参数映射到页面。 现在我们需要将其重命名为id。

现在用以下内容替换pages/post.js

  1. import Layout from '../components/MyLayout.js'
  2. import fetch from 'isomorphic-unfetch'
  3. const Post = (props) => (
  4. <Layout>
  5. <h1>{props.show.name}</h1>
  6. <p>{props.show.summary.replace(/<[/]?p>/g, '')}</p>
  7. <img src={props.show.image.medium}/>
  8. </Layout>
  9. )
  10. Post.getInitialProps = async function (context) {
  11. const { id } = context.query
  12. const res = await fetch(`https://api.tvmaze.com/shows/${id}`)
  13. const show = await res.json()
  14. console.log(`Fetched show: ${show.name}`)
  15. return { show }
  16. }
  17. export default Post

看看该页面的getInitialProps:

  1. Post.getInitialProps = async function (context) {
  2. const { id } = context.query
  3. const res = await fetch(`https://api.tvmaze.com/shows/${id}`)
  4. const show = await res.json()
  5. console.log(`Fetched show: ${show.Title}`)
  6. return { show }
  7. }

在那里,函数的第一个参数在context对象中。 它有一个我们可以用来获取信息的查询字段。

在我们的示例中,我们从查询参数中选择了显示ID,并从TVMaze API中获取了其显示数据。


在这个getInitialProps函数中,我们添加了一个console.log来打印显示标题。 现在我们来看看它打印的位置。

打开服务器控制台和客户端控制台。 然后访问主页 http://localhost:3000,然后点击第一个蝙蝠侠节目标题。

你在哪些地方看到上面提到的console.log消息?

  1. ✦在服务器控制台
  2. ✓在浏览器控制台
  3. ✦两个控制台
  4. ✦不要在任何控制台上打印