目录
- React Router V6 变更介绍
- 1. < Switch > 重命名为< Routes >
- 2. < Route >的新特性变更
- 3. 嵌套路由变得更简单
- 3.1 具体变化有以下:
- 3.2 废弃了V5中的Redirect
- 3.3 多个< Routes />
- 4. 用useNavigate代替useHistory
- 5. Hooks中新钩子useRoutes代替react-router-config
- 总结
React Router V6 变更介绍
之前一直在用5.x版本的Router,突然发现Router V6有一些变化,可以说是对嵌套路由更加友好了。这里,我们就做个简单的介绍。
1. < Switch > 重命名为< Routes >
之前在用Router时,需要用Switch包裹,Switch可以提高路由匹配效率(单一匹配) 。在V6中,该顶级组件将被重命名为Routes,注意的是其功能大部分保持不变。
2. < Route >的新特性变更
component/render被element替代
// v5 <Switch> <Route path="/about" component={About}/> <Route path="/home" component={Home}/> </Switch> //v6 <Routes> <Route path="/about" element={<About/>}/> <Route path="/home" element={<Home/>}/> </Routes>
3. 嵌套路由变得更简单
3.1 具体变化有以下:
- < Route children > 已更改为接受子路由。
- 比< Route exact >和< Route strict >更简单的匹配规则。
- < Route path > 路径层次更清晰。
function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About/>}> <Route path="/about/message" element={<Message/>} /> <Route path="/about/news" element={<News/>} /> </Route> </Routes> </BrowserRouter> ); } function About() { return ( <div> <h1>About</h1> <Link to="/about/message">Message</Link> <Link to="/about/news">News</Link> {/* 将直接根据上面定义的不同路由参数,渲染<MyProfile />或<OthersProfile /> */} <Outlet /> </div> ) }
这里的< Outlet /> 相当于占位符,像极了{this.props.children},也越来越像Vue了
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)