您现在的位置是:首页 >技术交流 >react-router-dom v5和v6版本对比网站首页技术交流
react-router-dom v5和v6版本对比
简介react-router-dom v5和v6版本对比
-
推荐使用函数组件
v5: 使用类式组件 v6: 推荐使用函数式组件,react-router-dom 中的api只能再函数式组件中使用(大多数api是hook函数)
-
用Routes替换原来的Switch组件
v5: <Switch> <Route path='/home' component={Home}/> <Route path='/about' component={About}/> </Switch> v6: <Routes> <Route path='/home' element={<Home/>}/> <Route path='/about' element={<About/>}/> </Routes>
-
用Navigate组件替换原来的Redirect组件
v5: <Switch> <Route path='/home' component={Home}/> <Route path='/about' component={About}/> <Redirect to='/home'/> </Switch> v6: <Routes> <Route path='/home' element={<Home/>}/> <Route path='/about' element={<About/>}/> <Route index element={<Navigate to='/home'/>}/> </Routes>
-
Route组件必须包裹在Routes组件里
v5: <Route path='/home' component={Home}/> <Route path='/about' component={About}/> v6: <Routes> <Route path='/home' element={<Home/>}/> <Route path='/about' element={<About/>}/> </Routes>
-
路由规则是默认严格匹配,匹配成功就不向下继续匹配
v5: 默认为模糊匹配,使用关键字exact才是精确匹配 <Switch> <Route exact path='/home' component={Home}/> <Route path='/about' component={About}/> </Switch> v6: <Routes> <Route path='/home' element={<Home/>}/> <Route path='/about' element={<About/>}/> </Routes>
-
嵌套路由(多级路由)
v5:必须要写明完整路由 <Switch> <Route path='/home' component={Home}/> <Route path='/about' component={About}/> <Redirect to='/home'/> </Switch> <Switch> <Route path='/home/news' component={News}/> <Route path='/home/message' component={Message}/> <Redirect to='/home/news'/> </Switch> v6:在一级路由中使用 /* 表示后面还有多级路由,在后面的路由中只须写明路由路径 xxx 即可, 不用写 /xxx <Routes> <Route path='/home/*' element={<Home/>}/> <Route path='/about' element={<About/>}/> <Route index element={<Navigate to='/home'/>}/> </Routes> <Routes> <Route path="news" element={<News/>}/> <Route path="message" element={<Message/>}/> <Route index element={<Navigate to="news"/>}/> </Routes>
-
定义路由规则匹配渲染组件语法改变
v5: component={Home} v6: element={<Home/>}
-
新增了多个hook函数,useParams、useSearchParams、useNavigate、useRoutes等
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。