how to access history object in new React Router v4

前端 未结 3 440
抹茶落季
抹茶落季 2020-12-29 09:07

I have tried all the suggested ways in other threads and it is still not working which is why I am posting the question.

So I have history.js looking li

相关标签:
3条回答
  • 2020-12-29 09:34

    I had this problem for a while and it was simply not having the withRouter connection.

    import { withRouter } from 'react-router';
    
    
    class Sample extends Component{
    
      render()
      {
    
         <button type="button" onClick={()=>{
                                    this.props.history.push('/');
                                    window.location.reload();    }}>
      }
    }
    
    export default withRouter(Sample);
    

    `

    0 讨论(0)
  • 2020-12-29 09:45

    Looks to me like you might be missing a withRouter connection. this would make the history props available to this component

    ...
    
    import { withRouter } from 'react-router'
    
    class Home extends Component {
      functionMethod() {
        const { history: { push } } = this.props;
        doStuff();
        push('/location');
      }
      ...
    }
    
    export default withRouter(Home);
    

    https://reacttraining.com/react-router/web/api/withRouter

    0 讨论(0)
  • 2020-12-29 09:47

    use the hook: useHistory

    import { useHistory } from "react-router-dom";
    
    function HomeButton() {
      let history = useHistory();
    
      function handleClick() {
        history.push("/home");
      }
    
      return (
        <button type="button" onClick={handleClick}>
          Go home
        </button>
      );
    }
    
    0 讨论(0)
提交回复
热议问题