1.封装公共组件
components/AuthRoute进行封装
// import React from 'react'
import { Redirect, Route } from 'react-router'
import PropTypes from 'prop-types'
import { hasToken } from '@/utils/token'
export default function AuthRoute ({ path, Component }) {
return (
<Route
path={path}
render={() => {
// 如果拥有token代表已经登录 就放行,否则没有登录,强制重定向到login
// hasToken是封装的判断有无token的
return hasToken() ? <Component /> : <Redirect to="/login" />
}}
/>
)
}
AuthRoute.propTypes = {
path: PropTypes.string.isRequired,
Component: PropTypes.func.isRequired
}
2.使用组件
路由时使用组件 跟普通Route使用方法一样 传入path和Component
注意点:传入的属性名Components的首字母大写,因为react强制建议组件必须大写
app根组件 直接进行使用
import React from 'react'
// import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import { Router, Route, Switch, Redirect } from 'react-router-dom'
import Login from '@/pages/Login/index.jsx'
import NotFound from './pages/NotFound/index.jsx'
import Layout from './pages/Layout/index.jsx'
import history from './utils/history.js'
import AuthRoute from './components/AuthRoute.js'
export default function App () {
return (
<Router history={history}>
<Switch>
<Redirect from="/" exact to="/login" />
<Route path="/login" component={Login} />
<AuthRoute
path="/home"
Component={() => {
return <Layout />
}}
/>
<Route path="/home" component={Layout} />
<Route component={NotFound} />
</Switch>
</Router>
)
}