【问题标题】:Nested Routes in React not rendering correctly with react-router v4React 中的嵌套路由无法使用 react-router v4 正确渲染
【发布时间】:2017-12-26 05:44:57
【问题描述】:

我的根组件主开关是这样的

<Provider store={createStoreWithMiddleware(reducers)}>
    <HashRouter history={history} >
      <Switch>
        <Route exact path="/login" name="Login Page" component={Login}/>
        <Route exact path="/register" name="Register Page" component={Register}/>
        <Route exact path="/404" name="Page 404" component={Page404}/>
        <Route exact path="/500" name="Page 500" component={Page500}/>
        <Route path="/Console" name="Console" component={Console}/>
        <Route path="/" name="Home" component={Full}/>
      </Switch>
    </HashRouter>
  </Provider>

Console 组件中,我定义了另一个开关,如下所示

<main className="container">
  <div className="">
    <Switch>
      <Route path="/Create" name="Create Park" component={CreateNew} />
      <Route path="/" name="Console" component={HomePage} />
    </Switch>
  </div>
</main>

当我访问/Console HomePage 组件时正确显示。

但是当我访问/Console/Create CreateNew 组件时不会显示,而是显示HomePage 组件。

我在这里做错了什么?我应该怎么做才能在/Console/Create 处显示CreateNew 组件

【问题讨论】:

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


    【解决方案1】:

    嵌套路由必须指定绝对路径,可以使用match.path作为嵌套路由的前缀来提供绝对路径

    <main className="container">
      <div className="">
        <Switch>
          <Route path={`${match.path}/Create`} name="Create Park" component={CreateNew} />
          <Route path={`${match.path}/`} name="Console" component={HomePage} />
        </Switch>
      </div>
    </main>
    

    或者指定完整路径

    <main className="container">
      <div className="">
        <Switch>
          <Route path="/Console/Create" name="Create Park" component={CreateNew} />
          <Route path="/Console/" name="Console" component={HomePage} />
        </Switch>
      </div>
    </main>
    

    根据 React-Router match 文档:

    匹配对象包含有关如何匹配的信息 网址。匹配对象包含以下属性:

    params - (object)从对应的URL解析出来的键值对 到路径的动态段

    isExact - (boolean) 如果整个 URL 都匹配,则为 true(没有尾随 字符)

    path - (string) 用于匹配的路径模式。对建筑有用 嵌套s

    url - (string) URL 的匹配部分。对建筑有用 嵌套s

    【讨论】:

      【解决方案2】:

      Console 组件重构如下:

      <main className="container">
            <div className="">
              <Switch>
                <Route exact  path="/" name="Console" component={HomePage} />
                <Route exact  path="/Create" name="Create Park" component={CreateNew} />
          </Switch>
        </div>
       </main>
      

      【讨论】:

        猜你喜欢
        • 2018-06-06
        • 2019-02-09
        • 2017-06-07
        • 2017-11-15
        • 2020-05-24
        • 2017-06-25
        • 2018-10-18
        相关资源
        最近更新 更多