Accessing Redux Store from routes set up via React Router

前端 未结 4 1212
暖寄归人
暖寄归人 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 07:28

    After trying out a few of the above suggestions, I found the best way to track the state of your store with updates is to use React-Redux's useSelector function which basically connects a functional component to the store.

    import * as React from "react";
    import {Redirect, Route, Switch} from "react-router";
    import {Provider, useSelector} from "react-redux";
    import { createBrowserHistory } from "history";
    
    // Your imports
    import {IApplicationState,} from "./store/store";
    import {Login} from "./routes/login/login.component";
    import {getToken} from "./store/helpers/httpHelpers";
    
    
    function handleRedirect() {
        if(!getToken()) {
            return ;
        }
    }
    
    const restricted = (Component: _ComponentType, isLoggedIn: boolean) => {
       // Don't redirect here if there is a token in localStorage.
       // This is happening when we are on a restricted route and the user
       // refreshes & the isLoggedIn state hasn't been updated yet.
        return !isLoggedIn ? (
            () => handleRedirect()
        ) : () => 
    };
    
    const AuthenticateRoutes = () => {
        const isLoggedIn = useSelector((state: IApplicationState) => state.auth.isLoggedIn);
        return (
            
                
                
            
        );
    };
    
    export function App() {
        return (
            
                <>
                    
                        
                    
                
            
        );
    }
    

提交回复
热议问题