加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – React路由器切换行为

发布时间:2020-12-15 20:46:34 所属栏目:百科 来源:网络整理
导读:(react-router-dom版本:4.1.1) 我有工作路线设置,但我有点困惑为什么 Switch是必要的: index.js import React from 'react';import { HashRouter,Route,Switch } from 'react-router-dom';import App from './components/App.jsx';import FridgePage from
(react-router-dom版本:4.1.1)

我有工作路线设置,但我有点困惑为什么< Switch>是必要的:

index.js

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

import App from './components/App.jsx';
import FridgePage from './components/FridgePage.jsx';

ReactDOM.render(
    <HashRouter>
        <Switch>
            <Route exact path="/" component={App} />
            <Route path="/fridge" component={FridgePage} />
        </Switch>
    </HashRouter>,document.getElementById('root')
)

App.jsx

import Header from './Header.jsx';
import {Link} from 'react-router-dom';

export default class App extends React.Component {
    render() {
        console.log(this.props);
        return (
            <div>
                <h1>Herbnew</h1>
                <Link to="fridge">Fridge</Link>
                {this.props.children}
            </div>
        );
    }
}

FridgePage.jsx

import React from 'react';

export default class FridgePage extends React.Component {
    render() {
        return (
            <div>
                <h1>Fridge</h1>
                You finally found the fridge!
            </div>
        );
    }
}

我曾经有一个div包裹路由而不是Switch.在这种情况下,我看到App呈现并尝试单击Fridge链接,但没有任何反应(FridgePage未呈现),并且没有错误输出到控制台.

据我所知,Switch所做的唯一事情是专门渲染它匹配的第一条路径,而省略它的常见问题是同时渲染两个页面.如果我的“/”路线是准确的,那么即使没有Switch,冰箱也应该是匹配的唯一路线,对吗?为什么它根本不渲染?

<开关和GT;仅返回第一个匹配的路由.

精确返回任意数量的匹配路由.

例如:

<Switch>
  <Route exact path="/animals" component={Animals} />
  <Route path="/animals/fish" component={Fish} />
  <Route component={Missing} />
</Switch>
<Route path="/animals" component={Contact} />

如果Missing组件不在< Switch>内,它将在每个路径上返回.

确切地说,“/ animals”路线也不会捕捉“/ animals / fish”路径.

如果没有确切的话,“/ animals / fish”路线也将返回“动物/鱼/鳕鱼”的鱼类成分.

在< Switch>之外声明,并且没有确切地说,Contact组件在包含“/ animals”的每个路径上呈现.

通常你会使用通配符,如果你不使用确切的,所以你不返回随机页面.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读