react-router-dom示例讲解(六)——未匹配(用于404页面)

前言:

倘若一个页面不存在,它就会跳到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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值