reactjs – React路由器切换行为

前端之家收集整理的这篇文章主要介绍了reactjs – React路由器切换行为前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
(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”的每个路径上呈现.

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

原文链接:https://www.f2er.com/react/300933.html

猜你在找的React相关文章