【问题标题】:Nested URL Routing in ReactJsReactJs 中的嵌套 URL 路由
【发布时间】:2019-08-02 22:43:50
【问题描述】:

要转到,我在Gatsby 中使用的competition page 这个函数,要转到那个页面:

gatsby-node.js

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions

  if (page.path.match(/^\/competition/)) {
    page.matchPath = "/competition/*"
    createPage(page)
  }
 }

来自competition page,我正在返回Game component

 return <Game path="/competition/:id" myid={ props.id }/>

然后在Game component 内,我正在渲染一个按钮以转到频道页面:

 <span className={style.button}>
     <Link to={'/competition/'+this.props.myid+'/'+rowdata['GameName']}/>
 </span>

在这里我不知道如何去channel page 我在src/pages 里面并保持我的网址像代码中一样:/competition/'+myid+'/'+GameName

我的方法正确吗? 我愿意接受其他解决方案

更新: 我可以接受这样的 url

<span className={style.button}>
     <Link to={'/competition/'+this.props.myid+'/channel'}/>
 </span>

【问题讨论】:

    标签: javascript reactjs url-routing gatsby


    【解决方案1】:

    我不熟悉 gatsby,但您似乎需要更严格地使用 API 根路径的正则表达式。

    if (page.path.match(/^\/competition/)) {
        page.matchPath = "/competition/*"
        createPage(page)
      }
    

    目前,上述匹配 '/competition'、'/competition9302n'、'/competition/903n/channel'...基本上任何以 '/competition' 开头的内容

    如果您想将“/competition/”视为与“/competition/some_id_here/channel”不同的路径,则需要定义两个(至少是更严格的根路径)不同的路径/路由。

    例如

    if (page.path.match(/^\/competition\/[0-9a-z].*$/i)) { // this will match only '/competition/<some_id_here>'
        page.matchPath = "/competition/*"
        createPage(page)
      } else if (page.path.match(/^\/competition\/[0-9a-z].*\/channel$/i)) {//this will match only '/competition/<some_id_here>/channel'
      }
    

    【讨论】:

    • 现在唯一有效的链接是/competition.. '/competition/' 不起作用加上 '/competition//channel' 404 页面返回
    • 你的“id”是由什么组成的?只有字母和数字?该正则表达式并不完美,您必须根据您的数据需求对其进行调整。此外,这些检查仅适用于“if”条件,请确保“page.matchPath”也映射到正确的正则表达式。
    • 我的身份证只是字母
    • 请您发布所有的“如果”条件。另外,我需要更具体的信息。什么不工作?页面没有渲染吗? 'if' 条件是否有效——程序传递到代码块中——但里面的代码没有触发?
    猜你喜欢
    • 1970-01-01
    • 2019-08-13
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 2021-05-16
    相关资源
    最近更新 更多