如果表单不完整,取消 componentWillUnmount

Cancel componentWillUnmount if a form is incomplete

我有一个带有 redux-form 的表单设置,基本上想创建一个场景,如果在任何表单输入中填充了内容,并且您尝试离开页面,您会收到提示。

目的是在他们单击 取消 时取消页面卸载或页面导航。我尝试创建一个条件,如果满足只会 return 但它仍然离开当前页面。

这可能很自然,我还不了解 react/react-router 工作流程,但暂时有人能解释一下最佳方法吗?如果有什么未满足,是否有一般的东西可以让我停止卸载?

import { reduxForm } from 'redux-form';

class Form extends Component {
  componentWillUnmount() {
    if (!this.props.pristine && !confirm('Are you sure you want to navigate away from this page?')) {
      return;
    }
  }

  render() {
    const { handleSubmit } = this.props;

    return (
      <form onSubmit={ handleSubmit(this.props.onSubmit) }>
        ...
      </form>
    );
  }
}

...

export default connect(mapStateToProps, null)(reduxForm({
  form: 'Form',
  enableReinitialize: true,
  validate
})(Form));

如果您使用的是 react-router,那么您可以点击 routerWillLeave;请参阅文档:https://github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md

更新

提供示例有点困难,这是粗略且未经测试的。

import { reduxForm } from 'redux-form';

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dirty: false
    };
  }

  componentDidMount() {
    this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave.bind(this));
  }

  routerWillLeave(nextLocation) {
    const { dirty } = this.state;

    if (dirty) {
      return 'You have unsaved information, are you sure you want to leave this page?'
    }
  }

  render() {
    const { handleSubmit } = this.props;

    return (
      <form onSubmit={ handleSubmit(this.props.onSubmit) }>
        ...
      </form>
    );
  }
}

基本上,只要用户尝试导航,routerWillLeave 就会触发。当用户进行更改时,将脏状态值更新为 true。该文档应涵盖您需要了解的其余部分(同时确保您的 运行 版本为 2.4.0+)。