【问题标题】:Why child route won't render without the parent route rendering?为什么没有父路由渲染子路由不会渲染?
【发布时间】:2019-08-24 08:38:24
【问题描述】:

我正在尝试导航到我正在呈现新页面的/movie/:title。但它仅在我的电影页面即/movie renders 时呈现,但我不希望我的电影页面在导航到/movie/:title 时被挂载。我只希望它作为路径的一部分。使/movie 路径精确不起作用,因为/movie/:title 不会与/movie 精确呈现。

App.js

class App extends React.Component {
 render() {
  return (
   <div>
      <Header />
      <Route path='/movies' component={Movies} />
      <Route path='/tvshows' component={TvShow} />      
   </div>
)}

电影.js

return (
   <div className="movies">
        <Route path={`${match.path}`} render={(props) => <CollectionGrid movies/>} />
        <Route path={`${match.path}`} render={(props) => <CollectionOverview movies/>} />
        <Route path={`${match.path}/:title`} component={ItemPage} />
   </div>
);

【问题讨论】:

  • 嗨 Shivam,请在下面查看我的解决方案,如果有帮助,请告诉我。

标签: reactjs react-router


【解决方案1】:

一些笔记。按照惯例,您应该将所有路由保存在一个路由器中,这样可以更轻松地导航和识别您的应用程序。

像这样组织你的路由器:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Home from "./Home";
import Movies from "./Movies";
import ItemPage from "./ItemPage";

const App = () => {
  return (
    <BrowserRouter>
      <div>
        <Switch>
          <Route path="/" component={Home} exact />
          <Route path="/movies/:title" component={ItemPage} />
          <Route path="/movies" component={Movies} />
        </Switch>
      </div>
    </BrowserRouter>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

此外,要解决您的解决方案,您需要Switch 组件,该组件在react-router-dom 中可用。 Switch 组件将查看Routes 的列表,并且只会呈现第一个Route path 字符串包含在URL 字符串中

在上面的列表中,我们有 3 条路线。如果你的 URL 是 "/movies/blah",它只会渲染 ItemPage 组件,因为该路由的 path 在列表中首先匹配。

出于这个原因,我们将"/movies/:title" 路由移到了常规"/movies" 之前。如果"/movies" 路由出现在列表的第一个位置,并且如果您的 URL 是 "/movies/blah",它仍然会满足 "/movies" 路由。这意味着 Switch 只会渲染 Movies 组件,这不是您想要的。

查看工作沙箱:https://codesandbox.io/s/hopeful-bogdan-lzl76

【讨论】:

  • 效果很好,谢谢。请问switch这里是做什么工作的?
  • 不客气!我可以编辑我的答案,以更深入地解释 Switch 正在做什么:)
  • @ShivamAima 酷让我知道这是否更有意义。请考虑投票并将其标记为解决方案:)
【解决方案2】:

您无法在此应用程序中直接访问匹配项,匹配项位于 this .props.match 你可以在

中使用它
const App({match})

那么当你需要使用它的时候应该

<Route path={`${match.path}`} render={(props) => <CollectionGrid movies/>} />

look to this example and explain

【讨论】:

    猜你喜欢
    • 2017-05-02
    • 2018-10-05
    • 2020-09-15
    • 1970-01-01
    • 2019-01-12
    • 2023-03-06
    • 2019-04-25
    • 1970-01-01
    • 2021-08-08
    相关资源
    最近更新 更多