react-导航守卫


在react中不像vue有专门的导航守卫,react路由实际上也是组件,利用组件的表达式制作配置导航守卫

路由原配置:<Route exact={true} strict={true} exact path='/home' component={Home} />

守卫配置:

<Route exact={true} strict={true} exact path='/home' render = {()=>(
isLogin ? (
<Home/>
)
:
(
<Redirect to="/login"/>
)
)}/>

component改成render表达式,添加isLogin判断字段(字段根据登录token等判定)每一个route组件都要配置比较麻烦:好处式不管显示导航与否:如果登录也有导航这时候每个导航按钮都可以切换路由,这样配置的导航不管点击哪个导航都会判断islogin并进入登录或指定页面

需要注意的点:在使用导航守卫方式配置路由的时候:render={()=>(...)}

 注意render时组件内的this.props获取不到history对象,component则可以如果用到在login组件内使用高阶函数:withRouter 

<Route exact={true} strict={true} exact path='/login' render={()=>(
<Login isLogin = {this.handlerLoginstatus}/>
)} />

这样在login组件内 就可以获取到props内的history对象了

整体步骤总结:

1:增加判断条件和isLogin辨析值

2:route配置改写render渲染判断组件

 <Route exact={true} strict={true} exact path='/home' render = {()=>(
                       isLogin ? (
                        <Home/>
                       )
                        :
                       (
                        <Redirect to="/login"/>
                       )
                   )}/>

3:login路由内渲染的login组件增加自定义事件用于子组件登录成功后通知跳转首页

<Route exact={true} strict={true} exact path='/login' render={()=>(
                        <Login isLogin = {this.handlerLoginstatus}/>
                   )} />
 handlerLoginstatus(){//子组件通知父组件更新登录状态-不然不会自动跳转到首页的
        console.log('handlerstatus触发了')
        this.setState({
            isLogin: true
        })
        console.log(this.state.isLogin)
    }

login.jsx

isLoginF(){
        this.props.isLogin()
        // 注意render时组件内的this.props获取不到history对象,component则可以如果用到在login组件内使用高阶函数:withRouter 
        console.log(this.props)
    }

如果不通知 登陆后跳转到首页将不会被更新因为判断的值isLogin更改后并没有刷新只是子组件更改了值所以要通知父组件更新isLogin值

子传父用自定义事件


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM