React-Route 4.0 舍去了路由钩子
为了实现在需要登录才能进入某个路由,说白了就是前端路由拦截
看例子实现的好像有点乱,自己这样实现了一下,不知道可以不可以,功能可以的
/*
* 登录验证
* */
import React from 'react';
import Login from '../pages/login'
import {Route} from 'react-router-dom'
const isEmptyChildren = (children) =>
React.Children.count(children) === 0
class AuthRoute extends Route {
render() {
//完全覆盖父类方法
const { match } = this.state
const { children, component, render } = this.props
const { history, route, staticContext } = this.context.router
const location = this.props.location || route.location
const props = { match, location, history, staticContext }
if (component){
if(!match) return null;
return this.state.isAuthed ? React.createElement(component, props) : React.createElement(Login, props)
}
if (render)
return match ? render(props) : null
if (typeof children === 'function')
return children(props)
if (children && !isEmptyChildren(children))
return React.Children.only(children)
return null
}
componentWillMount(){
//重写父类方法
super.componentWillMount();
const { match } = this.state;
if(match){
console.log('componentWillMount()')
this.auth();
}
}
componentWillReceiveProps(nextProps,nextContext){
//重写父类方法
super.componentWillReceiveProps(nextProps,nextContext);
const { match } = this.props;
if(match ){
console.log('componentWillReceiveProps')
this.auth();
}
}
auth(){
setTimeout(()=>{
this.setState({isAuthed:true})
},2000)
}
}
export default AuthRoute
楼主的这种实现复杂化了,官网的那个例子不是很简洁吗,在Route的render方法内做认证判断,从而决定是否渲染组件还是重定向到登录路由,不需要重写Route的原有方法。
以下是更新: