【问题标题】:Set and get URL parameters in Next.js在 Next.js 中设置和获取 URL 参数
【发布时间】:2019-04-11 18:25:13
【问题描述】:

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

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

变成这样……

/about/256983649012

然后在about页面中检索。

我该怎么做?

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

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

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

【问题讨论】:

    标签: reactjs react-router router next.js


    【解决方案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

    【讨论】:

      【解决方案2】:

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

      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}`)
          })
        })
      

      然后在你的关于页面:

      关于.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

      【讨论】:

      • 当我重新加载页面时,getInitialProps() 函数无法从 url 获取值。请问有什么解决办法吗?
      • 你能提供你的代码吗?或者尝试查看 getInitialProps() 的 props static getInitialProps (props) { console.log(props); }
      猜你喜欢
      • 2022-11-26
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 2019-12-10
      • 2018-03-09
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多