gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:41:22 25 4
gpt4 key购买 nike

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

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

我试过这样解决:

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() { /* */ }
}

有哪些更好的方法可以解决这个问题?谢谢!

最佳答案

您可以将 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() {
// ...
}
}

关于javascript - 在 React 中完成多个任务后提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55355018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com