Accessing Redux Store from routes set up via React Router

前端 未结 4 1218
暖寄归人
暖寄归人 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:42

    The easiest way to accomplish this is to pass your store to a function that returns your routes (rather than return your routes directly). This way you can access the store in onEnter and other react router methods.

    So for your routes:

    import React from 'react';
    import { Route, IndexRoute } from 'react-router';
    
    export const getRoutes = (store) => (
      const authRequired = (nextState, replaceState) => {
        // Now you can access the store object here.
        const state = store.getState();
    
        if (!state.user.isAuthenticated) {
          // Not authenticated, redirect to login.
          replaceState({ nextPathname: nextState.location.pathname }, '/login');
        }
      };
    
      return (
        
          
          
          
          
        
      );
    )
    

    Then update your main component to call the getRoutes function, passing in the store:

    
      
        { getRoutes(store) }
      
    
    

    As for dispatching an action from requireAuth, you could write your function like this:

    const authRequired = (nextState, replaceState, callback) => {
      store.dispatch(requireAuth())  // Assume this action returns a promise
        .then(() => {
          const state = store.getState();
    
          if (!state.user.isAuthenticated) {
            // Not authenticated, redirect to login.
            replaceState({ nextPathname: nextState.location.pathname }, '/login');
          }
    
          // All ok
          callback();
        });
    };
    

    Hope this helps.

提交回复
热议问题