Programmatically Navigate using react-router

前端 未结 8 1318
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 23:07

I am developing an application in which I check if the user is not loggedIn. I have to display the login form, else dispatch an action

相关标签:
8条回答
  • 2020-11-21 23:32

    This is my handle loggedIn. react-router v4

    PrivateRoute is allow enter path if user is loggedIn and save the token to localStorge

        function PrivateRoute({ component: Component, ...rest }) {
         return (
            <Route
              {...rest}
              render={props => (localStorage.token) ? <Component {...props} /> : (
                <Redirect
                  to={{
                    pathname: '/signin',
                    state: { from: props.location },
                  }}
                />
              )
              }
            />
          );
        }
    

    Define all paths in your app in here

    export default (
      <main>
        <Switch>
          <Route exact path="/signin" component={SignIn} />
          <Route exact path="/signup" component={SignUp} />
          <PrivateRoute path="/" component={Home} />
        </Switch>
      </main>
    );
    
    0 讨论(0)
  • 2020-11-21 23:33

    Those who are facing issues in implementing this on react-router v4. Here is a working solution for navigating through the react app programmatically.

    history.js

    import createHistory from 'history/createBrowserHistory'
    
    export default createHistory()
    

    App.js OR Route.jsx. Pass history as a prop to your Router.

    import { Router, Route } from 'react-router-dom'
    import history from './history'
    ...
    <Router history={history}>
     <Route path="/test" component={Test}/>
    </Router>
    

    You can use push() to navigate.

    import history from './history' 
    
    ...
    
    render() {
         if (isLoggedIn) {
             history.push('/test') // this should change the url and re-render Test component
         }
         // return login component
         <Login />
    }
    

    All thanks to this comment: https://github.com/ReactTraining/react-router/issues/3498#issuecomment-301057248

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