-component
---->sidebar.js
---->exampleTabOne.js
---->exampleTabTwo.js
---->exampleTabThree.js
--pages
---->setting(which include all sidebar and those exampletabs)
我的 nextJS 项目中确实有上述文件夹结构。 这里根据 nextjs 文档
在本地主机/设置上我可以轻松查看我的页面 但我想要实现的是如下所示:
1.localhost/setting/exampleTabOne
2.localhost/setting/exampleTabTwo/EXAMPLEID
3.localhost/setting/exampleTabThree/EXAMPLEID#something#something
带# 的最后一部分 Url 类似于内部选项卡内容,我有另一个选项卡,所以我想用 Hash url 修复它,这样虽然 ssr 我也可以轻松打开内部选项卡..
所以,你们能建议我如何解决这个问题吗?
最佳答案
这里,在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 路径名。
关于next.js - 接下来JS嵌套路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46262118/