How to use a custom component with react-router route transitions?

前端 未结 5 1546
生来不讨喜
生来不讨喜 2021-02-08 11:25

The article Confirming Navigation explains how to use a browser confirmation box in your transition hook. Fine. But I want to use my own Dialog box. If I were to use the methods

5条回答
  •  醉梦人生
    2021-02-08 11:42

    I made it work by setting a boolean on state whether you have confirmed to navigate away (using react-router 2.8.x). As it says in the link you posted: https://github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md

    return false to prevent a transition w/o prompting the user

    However, they forget to mention that the hook should be unregistered as well, see here and here.

    We can use this to implement our own solution as follows:

    class YourComponent extends Component {
      constructor() {
        super();
    
        const {route} = this.props;
        const {router} = this.context;
    
        this.onCancel = this.onCancel.bind(this);
        this.onConfirm = this.onConfirm.bind(this);
    
        this.unregisterLeaveHook = router.setRouteLeaveHook(
          route,
          this.routerWillLeave.bind(this)
        );
      }
    
      componentWillUnmount() {
        this.unregisterLeaveHook();
      }
    
      routerWillLeave() {
        const {hasConfirmed} = this.state;
        if (!hasConfirmed) {
          this.setState({showConfirmModal: true});
    
          // Cancel route change
          return false;
        }
    
        // User has confirmed. Navigate away
        return true;
      }
    
      onCancel() {
        this.setState({showConfirmModal: false});
      }
    
      onConfirm() {
        this.setState({hasConfirmed: true, showConfirmModal: true}, function () {
          this.context.router.goBack();
        }.bind(this));
      }
    
      render() {
        const {showConfirmModal} = this.state;
    
        return (
          
        );
      }
    }
    
    YourComponent.contextTypes = {
      router: routerShape
    };
    

提交回复
热议问题