Switch
- 默认情况下路由会从上至下匹配所有的 Route, 只要匹配都会显示
- 如果 Route 没有指定
path
, 那么表示这个 Route 和所有的资源地址都匹配
新建 Other.js:
import React from 'react';
class Other extends React.PureComponent {
render() {
return (
<div>Other</div>
)
}
}
export default Other;
App.js:
import React from 'react';
import Home from './components/Home'
import About from './components/About'
import Other from './components/Other'
import {BrowserRouter, HashRouter, Link, NavLink, Route, Routes} from 'react-router-dom';
class App extends React.PureComponent {
render() {
return (
<div>
<BrowserRouter>
<Link to={'/home'}>Home</Link>
<Link to={'/home/about'}>About</Link>
<Route path="/home" component={Home}/>
<Route path="/home/about" component={About}/>
<Route component={Other}/>
</BrowserRouter>
</div>
)
}
}
export default App;
在页面的体现就是不管你点击的是 Home 还是 About 都会显示 Other 组件出来,如果想要匹配到了之后就不在往后匹配了就需要使用如下的方案进行解决即可。
- 但是在企业开发中大部分情况下, 我们希望的是一旦有一个匹配到了后续就不要再匹配了
- 此时我们就可以通过 Switch 来实现
更改 App.js:
import React from 'react';
import Home from './components/Home'
import About from './components/About'
import Other from './components/Other'
import {BrowserRouter, HashRouter, Link, NavLink, Route, Routes, Switch} from 'react-router-dom';
class App extends React.PureComponent {
render() {
return (
<div>
<BrowserRouter>
<Link to={'/home'}>Home</Link>
<Link to={'/about'}>About</Link>
<Switch>
<Route exact path="/home" component={Home}/>
<Route exact path="/about" component={About}/>
<Route exact component={Other}/>
</Switch>
</BrowserRouter>
</div>
)
}
}
export default App;