react-router setRouteLeaveHook仍在更新URL

时间:2016-10-06 01:23:59

标签: javascript reactjs react-router react-router-redux

我使用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现在也是错误的。想法?

3 个答案:

答案 0 :(得分:3)

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;
       }
    })
  }
}

答案 1 :(得分:1)

如果您的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>
    )
  }
})

答案 2 :(得分:0)

this.routerWillLeave = this.routerWillLeave.bind(this)