【问题标题】:How to create subpages in NEXT.js如何在 NEXT.js 中创建子页面
【发布时间】:2019-05-04 06:14:13
【问题描述】:

我尝试获取一些子页面,例如

  • example.com/tests/project1
  • example.com/tests/project2

在 nextjs https://nextjs.org/

我能够创建像

这样的页面
  • example.com/page1
  • example.com/page2

通过把页面像

page1.js

在页面“文件夹”中,但我如何创建子页面,如

  • example.com/tests/page1
  • example.com/tests/page2

我尝试在 Pages 文件夹中创建子文件夹,但这不起作用并输出错误。

非常感谢您的帮助

【问题讨论】:

    标签: node.js reactjs react-native next.js


    【解决方案1】:

    您可以使用 express.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('/test/:page', (req, res) => {
          const page = req.params.page;
          let file = '';
          switch(page) {
             case 'page1':
                   file = '/page1';
                   break;
             case 'page2':
                   file = '/page2';
                   break;
             default:
                   file = '/page1';
          }
          return app.render(req, res, file, { page })
        })
    
        server.get('*', (req, res) => {
          return handle(req, res)
        })
    
        server.listen(port, (err) => {
          if (err) throw err
          console.log(`> Ready on http://localhost:${port}`)
        })
      })
    

    【讨论】:

    • 谢谢这是一个很好的解决方案,它只是破坏了我的路由,如果单击我想避免的链接,则需要重新加载页面。这是full code 我将链接添加到 components/Header.js 并且使用此路由解决方案,如果可以修复此链接,则必须在单击时刷新链接,这将是一个完美的解决方案。跨度>
    • 它现在可以工作了,只需要升级nextjs版本,会接受你的回答!
    【解决方案2】:

    在 pages 文件夹中创建一个 tests 文件夹,nextjs 会自动创建一个带有文件夹名称和您创建的页面的子路由。

    【讨论】:

      【解决方案3】:

      像@karin-bhandari 所说的那样在页面内创建测试文件夹。然后,您为每个子页面创建一个新文件夹,其中包含文件夹内的类或函数,因此在您的情况下,它将是:

      ./pages/tests/project1/project1.js

      ./pages/tests/project1/project2.js

      如果您有 tests 目录的动态路由,那么您可以有条件地呈现页面

      const Test = props => {
        const router = useRouter();
      
        return (
          <Layout>
            {router.query.subdirectory === "edit" ? (
              <EditPage />
            ) : (
              <Test id={router.query.id} data={props.data} />
            )}
          </Layout>
        );
      };
      

      其中id 是测试标识符,subdirectory 是子目录路径。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-19
        • 1970-01-01
        • 2013-11-02
        • 1970-01-01
        • 2021-03-31
        • 2011-03-31
        • 2015-01-25
        • 2016-11-29
        相关资源
        最近更新 更多