Nesting routes and dynamically routing in React-router v4

前端 未结 1 896
心在旅途
心在旅途 2020-12-02 02:47

I have following routing configuration:

return (
相关标签:
1条回答
  • 2020-12-02 03:09

    From what I can see of your React Router Design, you seem to be using React router version 4

    In that case you can specify the route in the Component Itself, and make use of withRouter to do a dynamic redirect like

    return (<div>
            <Router>
              <div>
    
                <Route path='/login' component={LoginPage}/>
                <EnsureLoggedInContainer/>
              </div>
            </Router>
          </div>
    );
    

    and

    import React from 'react';
    import { connect } from "react-redux";
    import {withRouter} from "react-router";
    
    class EnsureLoggedInContainer extends React.Component
    {
        componentDidMount() {
            if ( !this.props.isLoggedIn )
            {
                this.props.history.push('/login');
    
            }
        }
    
        render() {
            // console.log(this.props);
            if ( this.props.isLoggedIn )
            {
                return <Route path='/abc' component={abc} />
            }
            else
            {
                return null;
            }
        }
    
    
    }
    const mapStateToProps = (state,ownProps) => {
        return{
            isLoggedIn : state.isLoggedIn,
            // currentURL : this.props
        }
    }
    
    export default connect(mapStateToProps)(withRouter(EnsureLoggedInContainer));
    
    0 讨论(0)
提交回复
热议问题