gpt4 book ai didi

reactjs - 为什么我的组件一直在所有路由中渲染?

转载 作者:行者123 更新时间:2023-12-02 17:19:11 27 4
gpt4 key购买 nike

当我输入一个不存在的 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 时添加元素 路由。我很难尝试仅在我转到未定义的路线时才显示该消息。最初,我尝试切换路线并在顶部制作更“详细”的路线,如下所示:

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

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

最佳答案

你应该使用 <Switch> 成分。根据文档:

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

因此,从 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>

关于reactjs - 为什么我的组件一直在所有路由中渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44193807/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com