Programmatically navigate using react router

后端 未结 30 2300
無奈伤痛
無奈伤痛 2020-11-21 05:18

With react-router I can use the Link element to create links which are natively handled by react router.

I see internally it calls t

30条回答
  •  被撕碎了的回忆
    2020-11-21 05:29

    For React Router v4+

    Assuming that you won't be needing to navigate during the initial render itself (for which you can use component), this is what we are doing in our app.

    Define an empty route which returns null, this will allow you to get the access to the history object. You need to do this at the top level where your Router is defined.

    Now you can do all the things that can be done on history like history.push(), history.replace(), history.go(-1) etc!

    import React from 'react';
    import { HashRouter, Route } from 'react-router-dom';
    
    let routeHistory = null;
    
    export function navigateTo(path) {
      if(routeHistory !== null) {
        routeHistory.push(path);
      }
    }
    
    export default function App(props) {
      return (
        
           {
              routeHistory = history;
              return null;
            }}
          />
          {/* Rest of the App */}
        
      );
    }
    

提交回复
热议问题