react 路由优先级及 switch作用

本文详细探讨了React路由的优先级,指出children、component和render的匹配顺序为children > component > render。同时,解释了Switch组件的作用,它会独占路由,仅渲染第一个匹配的route或redirect,若无匹配项,可通过404路由进行处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此文主要介绍下react路由的优先级和switch的作用。

export default function App(props) {
  return (
    <div className="app">
      <Router>
        <Link to="/">首页</Link>
        <Link to="/user">用户中心</Link>
        <Link to="/login">登录</Link>
        <Link to="/product/123">商品</Link>

        <Switch>
          <Route
            exact
            path="/"
            //children={children}
            component={HomePage}
            //render={render}
          >
            {/* children 0000 */}
          </Route>
          <Route path="/user" component={UserPage} />
          <Route path="/login" component={LoginPage} />
          {/* <Route path="/product/:id" component={Product} /> */}
          <Route path="/product/:id" render={() => <Product />} />

          <Route component={_404Page} />
        </Switch>
      </Router>
    </div>
  );
}

function children(props) {
  return <div>children</div>;
}

function render(props) {
  console.log("render props", props); //sy-log
  return <div>render</div>;
}

代码如上可以验证,先去掉switch,然后匹配children,可以发现,children在每个路由变化之后都匹配到了,证明children不管是否匹配都会渲染。
注释掉children,解开component和render,可以发现component优先匹配,并且只有匹配到了才会渲染,由此可见,三者优先级为 children > component > render。
现在把switch放开,发现children只有在匹配之后才会渲染。说明switch是独占路由:返回第一个匹配的route或者redirect。如果没有找到,则可以设置一个404路由。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值