如果表单不完整,则取消 componentWillUnmount

IT技术 javascript reactjs redux redux-form
2021-05-05 18:05:15

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

目的是在单击Cancel 时取消页面卸载或页面导航我尝试创建一个条件,如果满足,它只会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));
1个回答

如果您使用的是 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+ 版)。