【问题标题】:NextJS and next-routes not routing as I would expectNextJS 和 next-routes 没有像我期望的那样路由
【发布时间】:2018-09-20 18:17:23
【问题描述】:

我创建了一个 routes.js 文件,如下所示:

const nextRoutes = require('next-routes');
const routes = module.exports = nextRoutes();

routes.add
    ('presenterallcurrent', '/presenter/:ccyear','speaker');
routes.add
    ('speakersessiondetail', '/presenter/:ccyear/:slugSpeaker','speakerdetail');

当我浏览到:

/presenter/2018/douglas-crockford-1124

我将被带到我的 /pages/speakerdetail.js 文件,其中 query.ccyear 和 query.slugSpeaker 填充为 2018 年和 douglas-crockford-1124

我期待当我浏览到

/presenter/2018

我将被带到 /pages/speaker.js,query.ccyear 设置为 2018

第二种情况按我的预期工作(/presenter/2018)确实将我带到 /pages/speaker.js,但是(/presenter/2018/douglas-crockford-1124 给了我一个 404。

我不明白什么,为什么这不起作用?

在我的 /pages/speaker 和 /pages/speakerdetail 中:

    static async getInitialProps({query}) {...}

【问题讨论】:

  • 您确定是 404 无法解析到 /pages/speakerdetail.js,还是该页面的 getInitialProps 中发生了导致 404 的问题?
  • 我在 getinitialprops 顶部有一个 console.log 没有被击中。
  • 文件名的大小写完全一致?
  • 我确实解决了这个问题。我有基础知识,只是一些语法问题。例如这里github.com/pkellner/next-routes-problem

标签: reactjs next.js


【解决方案1】:

对于路径中的可选参数,添加尾随 ? 并调整 speaker.js 以根据 query.slugSpeaker 是否未定义来呈现年视图或详细视图。

routes.add
    ('speaker', '/presenter/:ccyear/:slugSpeaker?');

【讨论】:

    猜你喜欢
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 2019-12-04
    相关资源
    最近更新 更多