为什么我的组件在所有路由中都保持渲染?

IT技术 reactjs typescript react-router-dom glamorous
2021-03-30 05:44:41

当我输入一个不存在的 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;

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

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>
);

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

1个回答

你应该使用一个<Switch>组件。根据文档:

这与仅使用一堆<Route>s 有何不同

<Switch>它的独特之处在于它专门呈现一条路线相比之下,每个<Route>与位置匹配的都包含渲染考虑这个代码:

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

如果 URL 是/about,则<About><User><NoMatch>都将呈现,因为它们都与路径匹配。这是设计使然,允许我们以<Route>多种方式s组合到我们的应用程序中,例如侧边栏和面包屑、引导标签等。

然而,有时我们只想选择一个<Route>进行渲染。如果我们在,/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>