【问题标题】:NextJS different page name from url nameNextJS 与 url 名称不同的页面名称
【发布时间】:2020-12-19 06:54:30
【问题描述】:

我在 NextJS 中做一个项目,但是我发现我的 pages 文件夹中的文件名表示 URL 栏中显示的路径。

有什么办法可以让我拥有这样的结构:


 - Pages
   - 1.jsx
   - 2.jsx
   - 3.jsx

然后将其渲染到 url 或路径:http://localhost:3000/about 其中3.jsx 将映射到 about 链接?

【问题讨论】:

    标签: javascript node.js reactjs next.js


    【解决方案1】:

    在 next.js 中创建自定义服务器

    关注this 官方文档。您可以管理代码中的每条路线。

    // server.js
    const { createServer } = require('http')
    const { parse } = require('url')
    const next = require('next')
    
    const dev = process.env.NODE_ENV !== 'production'
    const app = next({ dev })
    const handle = app.getRequestHandler()
    
    app.prepare().then(() => {
      createServer((req, res) => {
        // Be sure to pass `true` as the second argument to `url.parse`.
        // This tells it to parse the query portion of the URL.
        const parsedUrl = parse(req.url, true)
        const { pathname, query } = parsedUrl
    
        if (pathname === '/about') {
          app.render(req, res, '/3', query) // Pass the file name here so that it reads the proper file from /pages directory
        } else {
          handle(req, res, parsedUrl)
        }
      }).listen(3000, (err) => {
        if (err) throw err
        console.log('> Ready on http://localhost:3000')
      })
    })
    

    其他例子在这里:-

    【讨论】:

      【解决方案2】:

      您可以将页面内容分隔在不同的文件夹中(不映射/3),默认导出到about.jsx

      // someFolder/3.jsx
      export function AboutPage(){
        return <div>about</div>
      }
      
      // pages/about.jsx
      import { AboutPage } from '../somefolder/3.jsx'
      export default AboutPage
      

      我一直在使用这种结构来执行领域驱动开发、关注点分离以及更清晰地键入道具。唯一的问题是同时可视化静态道具和客户端获取有些困难。

      【讨论】:

        【解决方案3】:

        在 Next.js 中,页面是从 pages 目录中的文件导出的 React 组件。 页面根据其文件名与路线相关联。

        例如,在开发中:

        pages/index.js/ 路由相关联。

        pages/posts/first-post.js/posts/first-post 路由相关联。

        这就是您使用 Next.js 创建多个页面的方式。只需在 pages 目录下创建一个 JS 文件,文件的路径就变成了 URL 路径。您可以为它命名任何您喜欢的名称,只要在您的应用程序中保持一致性就可以了。

        此外,由于听起来您正在尝试控制页面的标题/元数据在浏览器中的显示方式,因此请务必查看这篇文章,其中详细解释了如何执行此操作。

        How to create custom page heads/metadata

        有关更多详细信息,您可以使用以下链接查看其他 Next.js 文档。

        Next.js basic page documentation

        A more complex article about dynamic routes

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-03-14
          • 2013-12-23
          • 2012-10-26
          • 1970-01-01
          • 2021-12-04
          • 1970-01-01
          • 2021-10-27
          相关资源
          最近更新 更多