繁体   English   中英

如何在 NEXT.js 中创建子页面

[英]How to create subpages in NEXT.js

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

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

在 nextjs https://nextjs.org/

我能够创建像

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

通过把页面像

页面1.js

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

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

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

帮助将不胜感激

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

您可以使用 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}`)
    })
  })

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

./pages/tests/project1/project1.js

./pages/tests/project1/project2.js

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

const Test = props => {
  const router = useRouter();

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM