【问题标题】:Differences between query routes in nextjs using next-routesnextjs 中使用 next-routes 查询路由的区别
【发布时间】:2019-01-30 09:36:46
【问题描述】:

我正在开发一个使用许多不同语言的 next.js 和 Reactjs 项目。所以我需要更改语言网址。示例:

www.example.com/es/entradas

www.example.com/en/tickets

www.example.com/de/eintrittskarten

为了制作路线,我看到有一个模块可以帮助我:next-routes

https://github.com/fridays/next-routes

有很多 url,我正在使用 CMS,所以我的客户可以添加更多,因此不能对路由进行编码。我想通过查询传递 url,如下所示:

const routes = require('next-routes');

module.exports = routes()
  .add('index', '/:lang?')
  .add('tickets', '/:lang?/:ticket')
  .add('hotel', '/:lang?/:hotel');

令我惊讶的是(如您所见),它不起作用,因为路线没有看到最后两条路线之间的区别。如果我写:

www.example.com/en/tickets

它会正确转到我的“门票”页面,但如果我写了

www.example.com/en/hotel

它会再次转到我的“门票”页面,而不是“酒店”

你知道我怎么做这个吗?


在我的项目中,我有这些与路线相关的文件:

server.js

const next = require('next');
const { createServer } = require('http');
const routes = require('./routes');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dir: './src/shared', dev });
const handle = routes.getRequestHandler(app);

app.prepare()
  .then(() => {
    createServer(handle)
  .listen(3001, (err) => {
    if (err) throw err;
    console.log("> Ready on http://localhost:3001");
  });
});

routes.js

const routes = require('next-routes');


module.exports = routes()
  .add('index', '/:lang?')
  .add('tickets', '/:lang?/:ticket')
  .add('hotel', '/:lang?/:hotel');

【问题讨论】:

    标签: javascript reactjs routes server-side-rendering next.js


    【解决方案1】:

    /en/hotel 的请求将转到“ticket”路由,因为它实际上匹配它。

    这是因为路线中“ticket”一词前面的:: 会将路由的一部分转换为具有该名称的参数。

    所以你可能想要的是:

    module.exports = routes()
      .add('index', '/:lang?')
      .add('tickets', '/:lang?/ticket')
      .add('hotel', '/:lang?/hotel');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-25
      • 2021-06-16
      • 2022-08-23
      • 2019-03-07
      • 2021-12-16
      • 2022-10-02
      • 2021-08-09
      • 1970-01-01
      相关资源
      最近更新 更多