next.js - 接下来JS嵌套路由

标签 next.js

-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/

相关文章:

jwt - 将 koa-jwt 与 koa-router 一起使用

javascript - 链接到 Next.js 中的动态路由

javascript - 为什么将 Next.js API 路由与外部 API 一起使用?

reactjs - NextJS Typescript 布局提示缺少 props

reactjs - 如何将 TailwindCSS 与 React 服务器组件 (Next.js) 结合使用

javascript - 如何将下一个/图像组件设置为 100% 高度

reactjs - 使用 React 配置 Solidity 合约的最佳方法是什么?

reactjs - EmotionJS 组件库中的组件未收到 Theme 属性

reactjs - 如何将 useContext 数据与属性一起使用

javascript - 将 url slug 添加到 Next Js 路由获取 TypeError 路径应该是类型字符串获取类型对象