react-router go back a page how do you configure history?

前端 未结 21 1260
说谎
说谎 2020-11-30 18:30

Can anyone please tell me how I can go back to the previous page rather than a specific route?

When using this code:

var BackButton = React.createCla         


        
21条回答
  •  死守一世寂寞
    2020-11-30 18:48

    Update with React v16 and ReactRouter v4.2.0 (October 2017):

    class BackButton extends Component {
      static contextTypes = {
        router: () => true, // replace with PropTypes.object if you use them
      }
    
      render() {
        return (
          
        )
      }
    }
    

    Update with React v15 and ReactRouter v3.0.0 (August 2016):

    var browserHistory = ReactRouter.browserHistory;
    
    var BackButton = React.createClass({
      render: function() {
        return (
          
        );
      }
    });
    

    Created a fiddle with a little bit more complex example with an embedded iframe: https://jsfiddle.net/kwg1da3a/

    React v14 and ReacRouter v1.0.0 (Sep 10, 2015)

    You can do this:

    var React = require("react");
    var Router = require("react-router");
    
    var SomePage = React.createClass({
      ...
    
      contextTypes: {
        router: React.PropTypes.func
      },
      ...
    
      handleClose: function () {
        if (Router.History.length > 1) {
          // this will take you back if there is history
          Router.History.back();
        } else {
          // this will take you to the parent route if there is no history,
          // but unfortunately also add it as a new route
          var currentRoutes = this.context.router.getCurrentRoutes();
          var routeName = currentRoutes[currentRoutes.length - 2].name;
          this.context.router.transitionTo(routeName);
        }
      },
      ...
    

    You need to be careful that you have the necessary history to go back. If you hit the page directly and then hit back it will take you back in the browser history before your app.

    This solution will take care of both scenarios. It will, however, not handle an iframe that can navigate within the page (and add to the browser history), with the back button. Frankly, I think that is a bug in the react-router. Issue created here: https://github.com/rackt/react-router/issues/1874

提交回复
热议问题