下一个JS嵌套路由

时间:2017-09-17 08:27:26

标签: next nextjs

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

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

我的 nextJS 项目中有上面的文件夹结构。 这里按照nextjs doc

在localhost / setting上我可以轻松查看我的页面 但我想要达到的目标如下:

1.localhost/setting/exampleTabOne
2.localhost/setting/exampleTabTwo/EXAMPLEID
3.localhost/setting/exampleTabThree/EXAMPLEID#something#something 

最后一部分带有#的Url就像内部标签内容我有另一个标签,所以我想用Hash url修复它,这样ssr我也可以轻松打开内部标签..

那么,请你们建议我如何解决这个问题?

1 个答案:

答案 0 :(得分: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路径名。