【问题标题】:Why does my component keep rendering in all routes?为什么我的组件一直在所有路由中呈现?
【发布时间】:2017-10-26 21:20:24
【问题描述】:

当我输入一个不存在的 url 时,我试图呈现一个组件。但是,组件会在所有路由中保持渲染。我正在使用react-router-dom@4.1.1。这是我设置的路线:

import * as React from "react";
import { Route, RouteComponentProps } from "react-router-dom";
import glamorous from "glamorous";
import ElementList from "./elementlist";
import AddElement from "./addelement";
import NotFound from "./NotFound";

const Styling = glamorous.div({
  minHeight: 5,
  minWidth: 8
});

const NavRouter = () => (
  <Styling>
    <Route path="/" exact={true} component={ElementList} />
    <Route path="/addelement" component={(props: 
       RouteComponentProps<{}>) => (
         <AddElement onSubmitSuccess={() => props.history.push("/")} />
       )} />
    <Route path="*" exact={true} component={NotFound}/>
  </Styling>
);

export default NavRouter;

这是我的NotFound 组件:

import * as React from "react";


const NotFound = () => (
  <h1>The page that you are looking is not there.</h1>
);

export default NotFound;

我目前面临的问题是,当我更改 URL 时,The page that you are looking is not there. 不断在//addelement 路由上弹出消息。我很难尝试仅在我转到未定义的路线时才显示该消息。最初,我尝试切换路线并在顶部制作更“详细”的路线,如下所示:

const NavRouter = () => (
  <Styling>
    <Route path="/addelement" component={(props: 
       RouteComponentProps<{}>) => (
         <AddElement onSubmitSuccess={() => props.history.push("/")} />
       )} />
    <Route path="/" exact={true} component={ElementList} />
    <Route path="*" component={NotFound}/>
  </Styling>
);

但是,它并没有解决问题。有没有办法防止消息出现在我去的每条路线上,除了未定义的路线?

【问题讨论】:

    标签: reactjs typescript react-router-dom glamorous


    【解决方案1】:

    您应该使用&lt;Switch&gt; 组件。根据文档:

    这与只使用一堆&lt;Route&gt;s 有何不同?

    &lt;Switch&gt; 的独特之处在于它独家呈现路线。相比之下,与位置匹配的每个&lt;Route&gt; 都会包含地呈现。考虑这段代码:

    <Route path="/about" component={About}/>
    <Route path="/:user" component={User}/>
    <Route component={NoMatch}/>
    

    如果 URL 是 /about,那么 &lt;About&gt;&lt;User&gt;&lt;NoMatch&gt; 将全部呈现,因为它们都与路径匹配。这是设计使然,允许我们以多种方式将&lt;Route&gt;s 组合到我们的应用程序中,例如侧边栏和面包屑、引导选项卡等。

    然而,有时我们只想选择一个&lt;Route&gt; 进行渲染。如果我们位于/about,我们不想同时匹配/:user(或显示我们的“404”页面)。

    因此,从react-router-dom导入:

    import { Route, RouteComponentProps, Switch } from 'react-router-dom';
    

    然后像这样应用它(注意不需要path="*"):

    <Switch>
      <Route path="/" exact={true} component={ElementList} />
      <Route path="/addelement" component={(props: 
         RouteComponentProps<{}>) => (
           <AddElement onSubmitSuccess={() => props.history.push("/")} />
         )} />
      <Route component={NotFound}/>
    </Switch>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-05
      • 2022-12-20
      • 2022-11-23
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多