react用高階組件實現路由守衛


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM