Performing Authentication on Routes with react-router-v4

前端 未结 1 1651
逝去的感伤
逝去的感伤 2020-11-27 21:51

I\'m trying to write Authentication checking for my DashBoard. But the function itself is not getting called. Can anyone give me some solution for

1条回答
  •  悲&欢浪女
    2020-11-27 22:43

    In react-router v4, you can make use of render prop to Route along with the lifecycle methods to replace the onEnter functionality existing in react-router v3.

    See this answer for more details:

    onEnter prop in react-router v4

    However since all you want to do is authentication in the onEnter prop, you could easily create a HOC that does that

    const RequireAuth = (Component) => { 
    
        return class App extends Component { 
        
            componentWillMount() { 
                const getToken = localStorage.getItem('token'); 
                if(!getToken) { 
                   this.props.history.replace({pathname: '/'}); 
                } 
            } 
            render() { 
               return  
            }
        } 
    
    } 
    
    export { RequireAuth }
    

    and use it like

    
    

    Edit: In case you need to make a network call to find if the use if authenticated of not, you would write the HOC like

     const RequireAuth = (Component) => { 
    
        return class App extends Component { 
            state = {
                isAuthenticated: false,
                isLoading: true
            }
        
            componentDidMount() {
                AuthCall().then(() => {
                    this.setState({isAuthenticated: true, isLoading: false});
                }).catch(() => {
                    this.setState({isLoading: false});
                })
            } 
            render() { 
               const { isAuthenticated, isLoading } = this.state;
               if(isLoading) {
                   return 
    Loading...
    } if(!isAuthenticated) { return } return } } } export { RequireAuth }

    Update:

    In addition to the HOC, you can also go for the PrivateRoute component like

    const PrivateRoute = ({component: Component, isAuthenticated, isLoading, ...rest }) => { 
               if(isLoading) {
                   return 
    Loading...
    } if(!isAuthenticated) { return } return } } } export { PrivateRoute };

    and you can use it like

      class App extends Component { 
            state = {
                isAuthenticated: false,
                isLoading: true
            }
        
            componentDidMount() {
                AuthCall().then(() => {
                    this.setState({isAuthenticated: true, isLoading: false});
                }).catch(() => {
                    this.setState({isLoading: false});
                })
            } 
            render() { 
               
                  
    } }

    0 讨论(0)
提交回复
热议问题