Check history previous location before goBack() react router v4

前端 未结 2 868
孤城傲影
孤城傲影 2020-12-14 07:57

My goal is to enable a \"Go Back\" button, but only if the route/path the user would go back to is in a certain category.

More precisely I have two kinds of Routes

相关标签:
2条回答
  • 2020-12-14 08:32

    While navigating though the Link component or even though history.push, you could pass the current location to another Route component

    like

    <Link to={{pathname: '/graph/1', state: { from: this.props.location.pathname }}} />
    

    or

    history.push({
      pathname: '/graph/1',
      state: { 
          from: this.props.location.pathname
      }
    })
    

    and then you could just get this location in your Component like this.props.location.state && this.props.location.state.from and then decide whether you wan't to goBack or not

    0 讨论(0)
  • 2020-12-14 08:39

    The history object has entries and the current index. I used these in the following way:

    var lastLocation = history.entries[history.index - 1];
    var lastUrl = lastLocation.pathname;
    
    0 讨论(0)
提交回复
热议问题