在使用路由的時候,有的時候我們的界面只能夠在登錄之后才可以看的到,這個時候就需要使用路由權限控制了
找了資料發現一個就是我使用的方法,一個是高階組件。 原諒菜鳥看不太懂不會使用高階組件…………
首先在路由中做一個私有權限的限制,限制里面的path就是你的私有界面
router.js
<Switch> <Route path="/" exact component={Home} /> <PrivateRoute path="/MyOptional" component={MyOptional} /> <Route render={() => <Redirect to="/" />} /> </Switch>
想要跳轉到path的里面,首先在PrivateRoute里面做登錄判斷條件
private.js
import React from 'react'; import {Route,Redirect,withRouter} from 'react-router-dom'; import PropTypes from 'prop-types'; //私有路由,只有登錄的用戶才能訪問 class PrivateRoute extends React.Component{ componentWillMount(){ let isAuthenticated = sessionStorage.getItem("userName") ? true :false; this.setState({isAuthenticated:isAuthenticated}) if(!isAuthenticated){ const {history} = this.props; setTimeout(() => { history.replace("/"); }, 1000) } } render(){ let { component: Component,path="/",exact=false,strict=false} = this.props; return this.state.isAuthenticated ? ( <Route path={path} exact={exact} strict={strict} render={(props)=>( <Component {...props} /> )} /> ) : <Redirect to={{ pathname: "/", }} //這里必須使用redireact不能和上面一樣使用<Route/> 因為會出現頁面先跳轉到myOption然后再跳轉到首頁的狀況,這樣用戶體驗不好 /> ; } } PrivateRoute.propTypes ={ path:PropTypes.string.isRequired, exact:PropTypes.bool, strict:PropTypes.bool, component:PropTypes.func.isRequired } export default withRouter(PrivateRoute);
這樣就ok了
注:因為我的登錄界面是在首頁或者各個界面的模態框,所以這里我的路徑直接都是如果沒有登錄,直接跳轉首頁的。如果大家的登錄界面是單獨的,那可以直接跳轉到登錄界面了
還有個tips就是,如果你的界面沒有在路由中進行聲明,然后又想要在界面中使用route相關的路徑參數,就可以引入withRouter,在this.props中得到了