简体   繁体   中英

How to create subpages in NEXT.js

I try to get some subpages like

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

in nextjs https://nextjs.org/

I was able to create pages like

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

by putting the pages like

page1.js

in the Pages "Folder" but how do I create subpages like

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

what I tried was creating subfolders in the Pages folder but this did not work and outputted errors.

Help would be much appreciated

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

You can use server like express.js and use the routing system:

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

Create the tests folder inside pages like @karin-bhandari said. You then create a new folder for each subpage with the class or function inside the folder, so in your case it would be:

./pages/tests/project1/project1.js

./pages/tests/project1/project2.js

If you have dynamic routing for the tests directory, then you could conditionally render a page

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

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

Where id is a test identifier and subdirectory is the subdirectory path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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