Next JS 嵌套路由

3
-component
---->sidebar.js
---->exampleTabOne.js
---->exampleTabTwo.js
---->exampleTabThree.js

--pages
---->setting(which include all sidebar and those exampletabs)

我在我的nextJS项目中有如下文件夹结构。 根据Next.js的文档,在localhost/setting上可以轻松查看我的页面, 但我想要实现以下目标:
1.localhost/setting/exampleTabOne
2.localhost/setting/exampleTabTwo/EXAMPLEID
3.localhost/setting/exampleTabThree/EXAMPLEID#something#something 

“Url”的最后一部分带有“#”,类似于选项卡内容中的另一个选项卡,因此我想使用哈希URL来修复它,这样在服务器端渲染时我也可以轻松打开该内部选项卡。 请问你们能否建议我如何解决这个问题?
1个回答

0

在 Next JS 中,我们可以通过在 server.js 文件中定义来实现这一点。

// This file doesn't go through babel or webpack transformation.
// Make sure the syntax and sources this file requires are compatible with the current node version you are running
// See https://github.com/zeit/next.js/issues/1245 for discussions on Universal Webpack or universal Babel
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 === '/setting/exampleTabOne') {
      app.render(req, res, '/setting', query);
    } else if (pathname === '/setting/exampleTabTwo/EXAMPLEID') {
      app.render(req, res, '/setting', query);
    } else {
      handle(req, res, parsedUrl);
    }
  }).listen(3000, err => {
    if (err) throw err;
    console.log('> Ready on http://localhost:3000');
  });
});

在设置页面中,我们可以根据 URL 路径名动态加载相应的组件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接