在相同级别的路径中反应路由器4模棱两可的匹配

时间:2018-10-26 08:07:21

标签: reactjs react-router-v4

用那些模棱两可的路径呈现正确的作曲的最佳方法是什么,目前无论传递什么值,它总是落在第一个匹配项中。

<Switch>
    <Route exact path={"/:vehicleclass/:categoryname/"} render={({ match, history }) => <Make history={history} match={match} {...props}/>} />
    <Route exact path={"/:vehicleclass/:manufacturername/"} render={({ match, history }) => <Year history={history} match={match} {...props}/>} />
    <Route exact path={"/:vehicleclass/:categoryname/:manufacturername/"} render={({ match, history }) => <Year history={history} match={match} {...props}/>} />
    <Route exact path={"/:vehicleclass/:manufacturername/:year/"} render={({ match, history }) => <Model history={history} match={match} {...props}/>} />
    <Route exact path={"/:vehicleclass/:year/:manufacturername/:model/"} render={({ match, history }) => <Value history={history} match={match} {...props}/>} />   </Switch>

2 个答案:

答案 0 :(得分:0)

如果我键入以下路径/sedan/foo,则路由器将仅匹配第一个,因为它无法知道您键入的是类别名称还是制造商名称。 (您没有sedan的确切路径,因此它将认为这是一个选项,并且将第一个选项与该选项匹配)

/:vehicleclass/:categoryname/ == /:vehicleclass/:manufacturername/,因为它将其视为/option1/option2

您需要将其视为category/:categoryname/vehicleclass/:vehicleclass,以便/category/option1/vehicleclass/option2有效

答案 1 :(得分:0)

您应在此类用例中参考其他约定,以便在前端设计网址路径:

示例:

对于最后一个,年份应使用查询参数传递,例如: :vehicleclass/manufacturer/:manufacturername/model/:model?year=2009

<Switch>
  <Route
    exact
    path={"/:vehicleclass/category/:categoryname/"}
    render={({ match, history }) => (
      <Make history={history} match={match} {...props} />
    )}
  />
  <Route
    exact
    path={"/:vehicleclass/manufacturer/:manufacturername/"}
    render={({ match, history }) => (
      <Year history={history} match={match} {...props} />
    )}
  />
  <Route
    exact
    path={
      "/:vehicleclass/category/:categoryname/manufacturer/:manufacturername/"
    }
    render={({ match, history }) => (
      <Year history={history} match={match} {...props} />
    )}
  />
  <Route
    exact
    path={"/:vehicleclass/manufacturer/:manufacturername/:year/"}
    render={({ match, history }) => (
      <Model history={history} match={match} {...props} />
    )}
  />
  <Route
    exact
    path={"/:vehicleclass/manufacturer/:manufacturername/model/:model"} 
    render={({ match, history }) => (
      <Value history={history} match={match} {...props} />
    )}
  />
</Switch>;