react-router setRouteLeaveHook 仍在更新 URL

react-router setRouteLeaveHook still updating URL

我正在使用 react 15.3.1,react-router 2.4.1 和 react-router-redux 4.0.5:

当我捕获路由更改时:

this.props.router.setRouteLeaveHook(
    this.props.route,
    this.routerWillLeave
);

private routerWillLeave = () => {
    if (this.state.editing)
        return 'You may have unsaved changes. Are you sure you want to leave?'
};

...我确实调用了我的 this.routerWillLeave 方法,但浏览器中的 URL 仍然发生变化,因此即使用户决定不离开页面而留在页面上, URL 现在是错误的。想法?

export default class extends Component {
  static contextTypes = {
    router: React.PropTypes.object.isRequired
  }

  state = {
    editing: true
  }

  componentDidMount() {

    this.context.router.setRouteLeaveHook(this.props.route, () => {
       if (this.state.editing) {
          return false;
          // At here you can give a confirm dialog, return true when confirm true
       }else {
           return true;
       }
    })
  }
}

如果你的react-route >2.4,你还可以使用withRouter来包装你的组件,这样可能会更好!

import React, {Component} from 'react';
import {render} from 'react-dom';
import {withRouter} from 'react-router';

export default withRouter(class extends Component {
  state = {
    unsaved: true
  }
  componentDidMount() {
    this.props.router.setRouteLeaveHook(this.props.route, () => {
      if (this.state.unsaved) {
        return false;
          // At here you can give a confirm dialog, return true when confirm true
       }else {
          return true;
       }
    })
  }
  render() {
    return (
      <div>
        <h2>About</h2>
        {this.props.children || "This is outbox default!"}
      </div>
    )
  }
})