前言:
倘若一个页面不存在,它就会跳到404页面,针对react即:
1、用一个没有path属性的Route(即404页面)去匹配任何路径;
2、Switch返回第一匹配成功的Route,只渲染第一个与当前访问地址匹配的<Route>或<Redirect>;
实现效果:
涉及代码:
class App extends Component{
render() {
return (
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/old-match">Old Match, to be redirected</Link></li>
<li><Link to="/will-match">Will Match</Link></li>
<li><Link to="/will-not-match">Will Not Match</Link></li>
<li><Link to="/also/will/not/match">Also Will Not Match</Link></li>
</ul>
<hr />
<Switch>
<Route path="/" exact component={Home}/>
<Redirect from="/old-match" to="/will-match"/>
<Route path="/will-match" component={WillMatch}/>
<Route component={NoaMatch}/>
</Switch>
</div>
</Router>
)
}
}
class Home extends Component{
render() {
return (
<h1>
1、一个没有path属性的Route可以被任何的路径匹配。
2、Switch返回的是第一个成功匹配到的Route。
</h1>
)
}
}
class WillMatch extends Component{
render(){
return(
<h1>
Matched
</h1>
)
}
}
class NoaMatch extends Component{
render(){
return(
<h1>No Match for {this.props.location.pathname}</h1>
)
}
}
倘若你还不理解请参考我的github上的这个示例:
https://github.com/guoqin721/react-router-dom6