Intercept/handle browser's back button in React-router?

前端 未结 12 1065
滥情空心
滥情空心 2020-11-27 03:47

I\'m using Material-ui\'s Tabs, which are controlled and I\'m using them for (React-router) Links like this:

    

        
12条回答
  •  清酒与你
    2020-11-27 04:26

    Version 3.x of the React Router API has a set of utilities you can use to expose a "Back" button event before the event registers with the browser's history. You must first wrap your component in the withRouter() higher-order component. You can then use the setRouteLeaveHook() function, which accepts any route object with a valid path property and a callback function.

    import {Component} from 'react';
    import {withRouter} from 'react-router';
    
    class Foo extends Component {
      componentDidMount() {
        this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave);
      }
    
      routerWillLeave(nextState) { // return false to block navigation, true to allow
        if (nextState.action === 'POP') {
          // handle "Back" button clicks here
        }
      }
    }
    
    export default withRouter(Foo);
    

提交回复
热议问题