[英]Return to caller function only after setState is complete
我是 reactjs 的新手。 我希望 function 仅在setState
发生后返回。 我的代码看起来像这样
state={ a: false, b: false } function1 = () =>{ this.setState({a: true}); //do something over here to wait until setState finishes //and then return to caller function } function2 = () =>{ this.setState({b: true}); //do something over here to wait until setState finishes //and then return to caller function } function3 = () =>{ function1(); function2(); if(this.state.a && this.state.b === true){ //perform something } }
如果我在单击按钮时调用function3()
,我不会得到所需的 output,因为 a 和 b 的 state 没有变为 true。 在 state 更新后,我如何//perform something
操作?
提前致谢。
如果我理解正确,您希望同时执行function1
和function2
然后执行检查。 由于setState
是异步的,您可以使用回调选项来解决每个 function 上的 promise,然后在function3
上等待两个承诺解决,然后执行您的检查。
请看这个例子:
state={
a: false,
b: false
}
function1 = () => {
return new Promise((resolve, reject) => {
this.setState({a: true}, () => resolve());
//do something over here to wait until setState finishes
//and then return to caller function
}
}
function2 = () => {
return new Promise((resolve, reject) => {
this.setState({b: true}, () => resolve());
//do something over here to wait until setState finishes
//and then return to caller function
}
}
function3 = () =>{
Promise.all([function1(), function2()]).then(() => {
if(this.state.a && this.state.b === true){
//perform something
}
});
}
希望能帮助到你!
不确定我是否理解您的问题,但setState()
需要回调 function ,如果在 state 已更新之后调用,因此对于您的示例,您可以像这样简化它:
state = {
a: false,
b: false
}
function1 = () => {
this.setState({a: true}, this.function3);
}
function2 = () => {
this.setState({b: true}, this.function3);
}
function3 = () => {
if(this.state.a && this.state.b === true){
//perform something
}
}
在 React 中设置 State 是一个异步操作,你必须异步处理,所以如果你想做一些在 setState 发生后执行的事情,你必须在回调 function 中执行此操作。
state={
a: false,
b: false
}
function1 = () =>{
this.setState({a: true}, this.function3);
}
function2 = () =>{
this.setState({b: true}, function3);
}
function3 = () =>{
if(this.state.a && this.state.b === true){
// Do what you want
}
}
setState
回调 function 是您在这里需要的:
根据您的代码,我建议这样做
state={
a: false,
b: false
}
function1 = () =>{
this.setState({a: true},() => {
//when setState finishes
this.checkState();
});
}
function2 = () =>{
this.setState({b: true},() => {
//when setState finishes
this.checkState();
});
}
function3 = () =>{
function1();
function2();
}
checkState() {
if(this.state.a && this.state.b === true){
//perform something
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.