react实现受保护路由的两种方式
通过高阶组件
import React, { Component } from 'react'
import {Route, withRouter} from 'react-router-dom'
import Storage from '@/utils/Storage'
class VerifyCmp extends Component {
componentDidMount() {
return Storage.get("islogin") || this.props.history.push("/login")
}
render() {
const Cmp = this.props.component
return (
<>
{
<Route path={this.props.path} render={(router) => {
return <Cmp {...router}></Cmp>
}}></Route>
}
</>
)
}
}
export default withRouter(VerifyCmp)
通过路由侦听
- 都是通过类组件进行的案例,函数组件同理可以进行高阶组件和路由侦听来实现路由保护
import React, { Component } from 'react';
import RouterView from './router'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import Storage from '@/utils/storage'
@connect(state => ({
footerMenu: state.getIn(['ck', 'footerMenu'])
}), null)
@withRouter
class App extends Component {
constructor(props) {
super(props);
this.accessUri = ['/fav', '/click']
}
checkLogin(pathname) {
const bool = this.accessUri.some(item => {
return new RegExp(item).test(pathname)
})
if (bool && !Storage.get('islogin')) {
this.props.history.push('/login')
return;
}
}
componentDidMount() {
this.checkLogin(this.props.location.pathname)
this.props.history.listen(location => {
this.checkLogin(location.pathname)
})
}
render() {
return (
<>
<h3 style={{ display: this.props.footerMenu }}>aaa</h3>
<RouterView />
</>
);
}
}
export default App;
函数组件hook路由侦听的实现
const App = () => {
const history = useHistory()
const checkLogin = (pathname) => {
console.log(123);
const bool = protectedRoute.some(item => {
return new RegExp(item).test(pathname)
})
if (bool && Storage.get('islogin') !== "") {
history.push('/login')
}
}
useEffect(() => {
checkLogin("/admin")
history.listen(location => {
checkLogin(location.pathname)
})
}, [history])
return (
<ConfigProvider locale={zhCN}> {}
<RouteList /> {}
<AuthRoute /> {}
</ConfigProvider >
);
}
export default App;
还有一种方式,通过在axios响应拦截器中实现拦截