Cancel componentWillUnmount if a form is incomplete

左心房为你撑大大i 提交于 2019-12-01 09:09:33

If you're using react-router, then you can tap into routerWillLeave; see the documentation: https://github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md

UPDATE

It's a bit tough to provide an example, this is rough and untested.

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

Basically routerWillLeave will fire anytime the user attempts to navigate. When a user makes a change, update the dirty state value to true. The documentation should cover the rest that you need to know (also make sure you're running version 2.4.0+).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!