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

时间:2018-11-08 09:04:05

标签: reactjs react-router router next.js

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

<Link href={`/about/${id}`}><a>About</a></Link>

要这样...

/about/256983649012

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

我该怎么做?

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

<Link href={{ pathname: 'about', query: { id: id }}}><a>About</a></Link>

但是我真的不希望链接像这样about?id=256983649012

3 个答案:

答案 0 :(得分:1)

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

server.js / app.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}`)
    })
  })

然后在您的“关于”页面中:

About.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>
  }
}

完整示例:here

答案 1 :(得分:-1)

看起来这里没有内置函数来创建路径。但是您可以将数组与join函数一起使用:

import Link from "next/link";

const id = 123;

export default () => (
  <div>
    Hello World.{" "}
    <Link href={{ pathname: ["about", id].join("/") }}>
      <a>About</a>
    </Link>
  </div>
);

它是用html代码创建的:

<a href="about/123">About</a>

答案 2 :(得分:-1)

您正在使用Next.js,因此实现此目的的正确方法是通过Next.js的路由系统。 这是通过文件夹结构完成的。你的看起来像这样:

/pages/   (this is provided by Next.js)
-- /about/  
---- [id].js
index.js   (homepage, provided by Next.js)

这将使您能够实现/ about / 256983649012,其id参数为256983649012。您页面的所有逻辑均输入[id] .js。

Next.js的文档非常好。在此处查看有关路由的更多信息:https://nextjs.org/docs/routing/introduction