How to push to History in React Router v4?

后端 未结 21 1894
不思量自难忘°
不思量自难忘° 2020-11-22 00:27

In the current version of React Router (v3) I can accept a server response and use browserHistory.push to go to the appropriate response page. However, this isn

21条回答
  •  遥遥无期
    2020-11-22 01:13

    step one wrap your app in Router

    import { BrowserRouter as Router } from "react-router-dom";
    ReactDOM.render(, document.getElementById('root'));
    

    Now my entire App will have access to BrowserRouter. Step two I import Route and then pass down those props. Probably in one of your main files.

    import { Route } from "react-router-dom";
    
    //lots of code here
    
    //somewhere in my render function
    
         (
          
    )} />

    Now if I run console.log(this.props) in my component js file that I should get something that looks like this

    {match: {…}, location: {…}, history: {…}, //other stuff }
    

    Step 2 I can access the history object to change my location

    //lots of code here relating to my whatever request I just ran delete, put so on
    
    this.props.history.push("/") // then put in whatever url you want to go to
    

    Also I'm just a coding bootcamp student, so I'm no expert, but I know you can also you use

    window.location = "/" //wherever you want to go
    

    Correct me if I'm wrong, but when I tested that out it reloaded the entire page which I thought defeated the entire point of using React.

提交回复
热议问题