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 }
                                }}
                            />
                        )
                }
            />
        );
    }
}

 

相关文章:

  • 2021-04-29
  • 2022-12-23
  • 2021-09-17
  • 2022-02-18
  • 2022-12-23
  • 2021-09-10
猜你喜欢
  • 2022-12-23
  • 2021-12-13
  • 2022-12-23
  • 2021-12-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案