【问题标题】:Cancel componentWillUnmount if a form is incomplete如果表单不完整,取消 componentWillUnmount
【发布时间】:2017-01-06 16:27:01
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs redux redux-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+ 版本)。

    【讨论】:

    • 您能根据我的代码提供一个示例吗?我尝试在 github 上实现示例代码,但一无所获。
    • 我收到index.js:23Uncaught TypeError: Cannot read property 'setRouteLeaveHook' of undefined
    • 我正在使用react-router": "^3.0.0 btw
    • 这取决于你的设置,你需要确保你使用的是withRouter:github.com/ReactTraining/react-router/blob/master/docs/…你也可以尝试旧的方式,但我不推荐那个路由:this.context.router.setRouteLeaveHook(route, this.routerWillLeave.bind(this));跨度>
    • 我认为您需要使用 withRouter() HOC 包装表单组件的导出以获得“this.props.router”:github.com/ReactTraining/react-router/blob/master/…
    猜你喜欢
    • 2018-09-29
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    相关资源
    最近更新 更多