react-router不像vue-router一樣有很多鈎子函數,可以做路由守衛。想實現路由守衛,可以用高階組件來實現。
@connect(state => ({ isLogin: state.user.isLogin })) class PrivateRoute extends Component { render() { const { isLogin, component: Component, ...rest } = this.props; ///Route組件里render和Component二選一 return ( <Route {...rest} //props 包含值:history,location,match //login 頁面可以通過 this.props.location.state.from知道是哪個頁面跳轉過來的,方便登錄后直接跳轉 render={props => isLogin ? ( <Component {...props} /> ) : ( <Redirect to={{ pathname: "/login", state: { from: props.location.pathname } }} /> ) } /> ); } }