当我输入不存在的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路由上总是会出现这样的消息:/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>
);但是,它没有解决这个问题。除了未定义的路由外,是否有办法防止消息出现在我要去的每一条路由上?
发布于 2017-05-26 04:58:37
您应该使用组件。根据文件:
这与仅仅使用一堆
<Route>有什么不同?<Switch>是唯一的,因为它只呈现一个路由。相反,与位置匹配的每个<Route>都具有包容性。请考虑以下代码: 如果URL是/about,那么<About>、<User>和<NoMatch>都会呈现,因为它们都匹配路径。这是通过设计实现的,允许我们以多种方式将<Route>组合到我们的应用程序中,比如侧边栏和面包屑、引导选项卡等等。 然而,有时我们只希望选择一个<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>https://stackoverflow.com/questions/44193807
复制相似问题