1、根据路径加载对应页面内容
2、路由跳转
3、路由懒加载
4、嵌套路由(子路由)
5、路由管理
6、路由跳转权限校验
"react": "^17.0.2"
"react-router-dom": "^5.2.0"
1、根据路径加载对应页面内容
***App.js***
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'
import {Suspense} from 'react'
//routes是路由列表配置,将在下面展示
import routes from './router/index'
function App() {
return (
<div className="App">
//这里Suspense是用于和React.lazy配合使用的
<Suspense fallback={<div>loading...</div>}>
<Router>
<Switch>
{routes.map((item,index) => (<Route exact={item.isExact} component={item.component} path={item.path} key={index}/>))}
</Switch>
</Router>
</Suspense>
</div>
);
}
export default App;
***routes列表管理***
import React from 'react'
const routes = [
{
path: '/',
component: React.lazy(() => import('../pages/home/index')),
// 如果要求严格路径
isExact: true,
meta:{
title: '首页'
}
},
{
path: '/eg',
component: React.lazy(() => import('../pages/eg/index')),
meta:{
title: '案例页面'
}
}
]
export default routes
2、路由跳转
**这里我们使用useHistory这个hook来实现跳转
import {useHistory} from 'react-router-dom'
let Content = () => {
let history: any;
history = useHistory()
let goPage: () => void;
goPage = () => {
history.push('/eg/one')
}
return(
<div className="box">
案例页面
<div onClick={goPage}>跳转</div>
</div>
)
}
export default Content
3、路由懒加载
路由的懒加载,我们选择使用React.lazy、Suspense的组合
import React from 'react'
React.lazy(() => import('../pages/home/index'))
4、嵌套路由(子路由)
因为react-router没有像vue一样的children,所以需要我们自己处理子路由;
在需要使用子路由是,我们将不能在父级路由使用exact属性,如果使用了,将无法到达子路由;
*App.js中代码片段*
<Switch>
{routes.map((item,index) => (<Route exact={item.isExact} component={item.component} path={item.path} key={index}/>))}
</Switch>
然后,我们在我们的父路由组件中,嵌入我们的子路由Route即可
*父路由组件*
let parent = () => {
return(
<div className="box">
案例页面
<div onClick={goPage}>跳转</div>
//在这里嵌入我们的子路由即可
<Route exact component={One} path="/eg/one"/>
</div>
)
}
5、路由管理
routes路由列表
import React from 'react'
const routes = [
{
path: '/',
component: React.lazy(() => import('../pages/home/index')),
// 如果要求严格路径
isExact: true,
meta:{
title: '首页'
}
},
{
path: '/eg',
component: React.lazy(() => import('../pages/eg/index')),
meta:{
title: '案例页面'
}
}
]
export default routes
然后我们将其在Router进行循环即可
App.js代码片段
<Router>
<Switch>
{routes.map((item,index) => (<Route exact={item.isExact} component={item.component} path={item.path} key={index}/>))}
</Switch>
</Router>
6、路由跳转权限校验
因为react-router中暂时没有beforeRouter这类的api,所以我们需要自己处理相关路由校验;
**定义标签逻辑,内部包含登录判断
const RequireAuth = ({ children }) => {
if (Auth.isLogin) {
return <Redirect to="/login" />;
}
return children;
}
**把需要校验的路由放到标签内部即可
<RequireAuth>
<Route exact component={One} path="/eg" />
</RequireAuth>
**但是需要先渲染login
<Route path="/login" component={Login} />