我想在完成多个任务后调用表单提交功能。
任务可以按任何顺序完成。
我试图这样解决:
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() { /* */ }
}
解决此问题的更好方法有哪些?谢谢!
答案 0 :(得分:1)
您可以将imageUploaded
和submitButtonClicked
存储在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() {
// ...
}
}