Accessing Redux Store from routes set up via React Router

前端 未结 4 1210
暖寄归人
暖寄归人 2021-01-30 07:20

I would like to make use of react-router\'s onEnter handler in order to prompt users to authenticate when entering a restricted route.

So far my route

4条回答
  •  清酒与你
    2021-01-30 07:38

    If you want that you could write route.js like this:

    var requireAuth = (store, nextState, replace) => {
      console.log("store: ", store);
      //now you have access to the store in the onEnter hook!
    }
    
    export default (store) => {
      return (
          
            
            
            
            
          
        );
    );
    

    I've setup an example which you could play with in this codepen.

    Not sure if triggering an action in order to handle the auth is a good idea. Personally I prefer handling auth in a different way:

    Instead of using an onEnter hook, I use a wrapping function. I want the admin section of my blog protected, therefore I wrapped the AdminContainer component in the routes with a function, requireAuthentication, see below.

    export default (store, history) => {
            return (
                
                    
                        { /* Home (main) route */ }
                        
                        
                        { /*  */ }
                    
    
                    
                        
                        
                        
                    
                    
                
            );
        };
    

    requireAuthentication is a function that

    • if the user is authenticated, renders the wrapped component,
    • otherwise redirects to Login

    You can see it below:

    export default function requireAuthentication(Component) {
        class AuthenticatedComponent extends React.Component {
    
            componentWillMount () {
                this.checkAuth();
            }
    
            componentWillReceiveProps (nextProps) {
                this.checkAuth();
            }
    
            checkAuth () {
                if (!this.props.isAuthenticated) {
                    let redirectAfterLogin = this.props.location.pathname;
                    this.context.router.replace({pathname: '/login', state: {redirectAfterLogin: redirectAfterLogin}});
                }
            }
    
            render () {
                return (
                    
    {this.props.isAuthenticated === true ? : null }
    ) } } const mapStateToProps = (state) => ({ isAuthenticated: state.blog.get('isAuthenticated') }); AuthenticatedComponent.contextTypes = { router: React.PropTypes.object.isRequired }; return connect(mapStateToProps)(AuthenticatedComponent); }

    Also, requireAuthentication will protect all routes under /admin. And you can reuse it wherever you like.

提交回复
热议问题