小编典典

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

reactjs

我有一个带有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));

阅读 233

收藏
2020-07-22

共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+)。

2020-07-22