在React中完成多个任务后提交表单

时间:2019-03-26 10:35:18

标签: javascript reactjs

我想在完成多个任务后调用表单提交功能。

任务可以按任何顺序完成。

我试图这样解决:

function callbackWhenCompleted(callback) {
  let tasks = {
    imageUploaded: false,
    submitButtonClicked: false
  };

  function taskCompleted(taskName) {
    tasks[taskName] = true;
    if (Object.values(tasks).every(Boolean)) {
      callback();
    }
  }

  return taskCompleted;
}

class Form extends React.Component {
  componentDidMount() {
    this.taskCompleted = callbackWhenCompleted(this.submitForm);
  }

  imageUploaded = () => this.taskCompleted('imageUploaded');
  submitButtonClicked = () => this.taskCompleted('submitButtonClicked');
  submitForm = () => { /* */ }
  render() { /* */ }
}

解决此问题的更好方法有哪些?谢谢!

1 个答案:

答案 0 :(得分:1)

您可以将imageUploadedsubmitButtonClicked存储在Form组件状态中,并在更改其中之一并调用submitForm后检查它们是否为真

示例

class Form extends React.Component {
  state = {
    imageUploaded: false,
    submitButtonClicked: false
  };

  imageUploaded = () => {
    this.setState({ imageUploaded: true }, this.checkIfComplete);
  };

  submitButtonClicked = () => {
    this.setState({ submitButtonClicked: true }, this.checkIfComplete);
  };

  checkIfComplete = () => {
    const { imageUploaded, submitButtonClicked } = this.state;

    if (imageUploaded && submitButtonClicked) {
      this.submitForm();
    }
  };

  submitForm = () => {
    // ...
  };

  render() {
    // ...
  }
}