簡體   English   中英

僅在 setState 完成后返回調用方 function

[英]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操作?

提前致謝。

如果我理解正確,您希望同時執行function1function2然后執行檢查。 由於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
  }
}

看看這個關於使用 setState 回調的例子

在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM