Why does my component keep rendering in all routes?

穿精又带淫゛_ 提交于 2019-11-29 08:58:53

You should use a <Switch> component. Per the documentation:

How is this different than just using a bunch of <Route>s?

<Switch> is unique in that it renders a route exclusively. In contrast, every <Route> that matches the location renders inclusively. Consider this code:

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

If the URL is /about, then <About>, <User>, and <NoMatch> will all render because they all match the path. This is by design, allowing us to compose <Route>s into our apps in many ways, like sidebars and breadcrumbs, bootstrap tabs, etc.

Occasionally, however, we want to pick only one <Route> to render. If we’re at /about we don’t want to also match /:user (or show our “404” page).

Thus, import it from react-router-dom:

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

Then apply it like so (note there is no need for path="*"):

<Switch>
  <Route path="/" exact={true} component={ElementList} />
  <Route path="/addelement" component={(props: 
     RouteComponentProps<{}>) => (
       <AddElement onSubmitSuccess={() => props.history.push("/")} />
     )} />
  <Route component={NotFound}/>
</Switch>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!