我的React应用程序中有此方法:
我的问题是createQuestions()
在完成findEmployeeId()
方法之前运行。 .then
是否应该等待?
在findEmployeeId()
内部,它正在执行setState
操作。它不等到完成吗?在运行createQuestions()
之前,我需要更新数据。
createInterview() {
fetch(API_URL + `/interview/create`, {
method: "PUT",
body: JSON.stringify({
employee: this.state.employee,
employment_level: this.state.employment_level,
audit_id: this.props.auditId,
}),
headers: { "Content-Type": "application/json" },
})
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.catch((err) => console.log(err))
.then(() => this.findEmployeeId())
.then(() => this.createQuestions());
this.setState({ showHide: false });
}
这是findEmployeeId
方法。如何让它等到下一个运行完成之前?
findEmployeeId() {
fetch(API_URL + `/employee/${this.state.employee}/${this.props.auditId}`)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((result) => {
this.setState({ lastEmployeeId: result[0].employee_id });
console.log(result);
})
.catch((error) => {
console.log(error);
});
}
答案 0 :(得分:-1)
@ raina77ow已经在他的评论中写了它,但是要更清楚地陈述一下,我认为您需要从findEmployeeId()返回诺言:
findEmployeeId() {
/* Note the return here */
return fetch(API_URL + `/employee/${this.state.employee}/${this.props.auditId}`)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((result) => {
this.setState({ lastEmployeeId: result[0].employee_id });
console.log(result);
})
.catch((error) => {
console.log(error);
});
}
答案 1 :(得分:-2)
问题基本上是找到一种方法来保证在findEmployeeId()之后执行createQuestions()。这是问题的核心。使用setState回调可以使这种情况发生。据说使用setState回调可能很麻烦,但是如果对两个函数的组成有了很好的了解,那么就不应该了。
setState是异步的...因此,不要对两个操作的顺序进行假设是很重要的:
this.setState({stateA : a})
this.setState({stateB : b})
通过setState“强制”顺序的唯一方法是通过其回调:
this.setState({....},()=> {完成setState之后执行})
这就是您需要遵循的方式,即在findEmployeID内部使用的setState处,必须执行以下操作:
const self = this;
this.setState({ ..... }, () => {self.createQuestions()})
谁把那个否定性更好地解释了他的原因。提取的.then部分不能保证顺序,因此它会遇到两个setState依次执行的情况。等待也不能保证顺序。