Programmatically Navigate using react-router

前端 未结 8 1323
佛祖请我去吃肉
佛祖请我去吃肉 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: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'
    ...
    
     
    
    

    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
         
    }
    

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

提交回复
热议问题