在 Next.js 中设置和获取 URL 参数

Rub*_*uby 5 router reactjs react-router next.js

我想知道如何在 Next.js 中的 URL 末尾附加一个 ID,以及如何像这样在目标页面中检索它......

<Link href={`/about/${id}`}><a>About</a></Link>
Run Code Online (Sandbox Code Playgroud)

变成这样...

/about/256983649012
Run Code Online (Sandbox Code Playgroud)

然后在关于页面中检索它。

我怎样才能做到这一点?

请记住,我已经知道这种方法......

<Link href={{ pathname: 'about', query: { id: id }}}><a>About</a></Link>
Run Code Online (Sandbox Code Playgroud)

但我真的不想链接变成这样 about?id=256983649012

Dar*_*ert 3

您需要在 server.js / app.js 中定义该 id (我在这里使用 Express):

服务器.js/应用程序.js

const express = require('express')
const next = require('next')

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare()
  .then(() => {
    const server = express()

    server.get('/about/:id', (req, res) => {
      return app.render(req, res, '/about', { id: req.params.id })
    })

    server.get('*', (req, res) => {
      return handle(req, res)
    })

    server.listen(port, (err) => {
      if (err) throw err
      console.log(`> Ready on http://localhost:${port}`)
    })
  })
Run Code Online (Sandbox Code Playgroud)

然后在您的关于页面中:

关于.js

import React, { Component } from 'react'

export default class extends Component {
  static getInitialProps ({ query: { id } }) {
    return { aboutId: id }
  }

  render () {
    return <div>
      <h1>About #{this.props.aboutId}</h1>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua.
      </p>
    </div>
  }
}
Run Code Online (Sandbox Code Playgroud)

完整的例子:这里