在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值
子傳父用自定義事件
