【问题标题】:Split react router keeps matching 404 route on all routes拆分反应路由器在所有路由上保持匹配 404 路由
【发布时间】:2021-12-31 15:24:44
【问题描述】:

将我的路线分成两个(现在,以后是四个)独立的组件。

const RouterComponentOne = () => {
  return (
    <Switch>
      <Route path="/routeA" component={ComponentA} />
      <Route path="/routeB" component={ComponentB} />
    </Switch>
  )
}

const RouterComponentTwo = () => {
  return (
    <Switch>
      <Route path="/routeC" component={ComponentA} />
      <Route component={Component404} />
    </Switch>
  )
}

const RouterDefault = () => {
  return (
    <>
      <RouterComponentOne />
      <RouterComponentTwo />
    </>
  )
}

export default RouterDefault;

当访问来自RouterComponentOne 的任何路由时,404 组件会被渲染(它不应该这样做)。它呈现在不存在的路线上(例如/test/123/abc,这是正确的,并且不会在任何RouterComponentTwo 路线上呈现。 我在RouterDefault404 组件中添加了一些虚拟组件,并在所有其他路径上呈现。

简而言之,404 路由在 404Route 所在的组件的路由中不匹配/呈现。如果放入RouterComponentOne,它不会在routeArouteB 上渲染,但会在routeC 上渲染

我该如何解决这个问题?

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    你需要一个名为exact的属性

    const RouterComponentOne = () => {
      return (
        <Switch>
          <Route path="/routeA" exact component={ComponentA} />
          <Route path="/routeB" exact component={ComponentB} />
        </Switch>
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-27
      • 2017-08-06
      • 1970-01-01
      • 2022-01-14
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多