Javascript 是否。然后等待setState完成,然后再调用下一个方法?
我的React应用程序中有此方法: 我的问题是Javascript 是否。然后等待setState完成,然后再调用下一个方法?,javascript,reactjs,Javascript,Reactjs,我的React应用程序中有此方法: 我的问题是createQuestions()在findeEmployeeId()方法完成之前运行。那么,。难道不应该让它等待吗 在findeEmployeeId()内部,它正在执行setState操作。它不是要等那件事结束吗?我需要在运行createQuestions()之前更新数据 createInterview() { fetch(API_URL + `/interview/create`, { method: "PUT&qu
createQuestions()
在findeEmployeeId()
方法完成之前运行。那么,。难道不应该让它等待吗
在findeEmployeeId()
内部,它正在执行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 });
}
这是findeemployeeid
方法。我怎样才能让它等到完成后再运行下一个
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);
});
}
问题主要在于找到一种方法来保证在findeEmployeeId()之后执行createQuestions()。这是问题的核心。使用setState回调可以实现这一点。据说setState回调的使用可能会很麻烦,但如果对两个函数的组成有很好的理解,那么就不应该这样
设置状态是异步的。。。因此,重要的是不要对两项行动的顺序性做出假设,如:
this.setState({stateA : a})
this.setState({stateB : b})
通过setState“强制”顺序的唯一方法是通过其回调:
this.setState({….},()=>{setState完成后的do})
不知何故,这是您需要遵循的,即在findEmployeID内部使用的设置状态下,有必要执行以下操作:
const self = this;
this.setState({ ..... }, () => {self.createQuestions()})
不管是谁,最好解释一下他的理由。fetch的.then部分不能保证顺序性,因此它会出现类似的情况,即两个SETSTATE一个接一个地执行。等待也不能保证顺序性。@raina77ow已经在他的评论中写到了这一点,但要说得更清楚一点,我认为你需要回报findEmployeeId()的承诺:
>难道不是吗。那就让它等一下吧不,除非findEmployeeId回复一个承诺。这是有道理的,而且成功了。非常感谢你!问题主要在于找到一种方法来保证在findeEmployeeId()之后执行createQuestions()。这是问题的核心。使用setState回调可以实现这一点。据说setState回调的使用可能会很麻烦,但如果对两个函数的组成有很好的理解,那么这就不应该了。@JoseCabreraZuniga我谦虚地不同意。我认为这个问题主要是关于为什么代码不能按预期工作。我仍然认为这是因为它没有从函数返回承诺。这类内容很容易被忽略,这也是我自己使用typescript的主要原因。问题是:“我需要在createQuestions()运行之前更新数据。”
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);
});
}