Javascript 同步地反应本机运行函数

Javascript 同步地反应本机运行函数,javascript,react-native,ecmascript-6,Javascript,React Native,Ecmascript 6,我已经编写了以下代码,它运行顺利,但我遇到了一个问题: submitFormToBackend = async () => { if (this.paymentMethod === 'apple-pay') { this.setState({ showLoadingIndicator: true }); // <-- below await setTimeout can confirm this line run before it } let requeste

我已经编写了以下代码,它运行顺利,但我遇到了一个问题:

submitFormToBackend = async () => {
  if (this.paymentMethod === 'apple-pay') {
    this.setState({ showLoadingIndicator: true }); // <-- below await setTimeout can confirm this line run before it
  }

  let requester = new ApplePayRequester({...this.form});
  let applePay = new ApplePay();

  await setTimeout(async () => {
    let cardTokenResponse = await applePay.getCardToken();
    if (cardTokenResponse.isSuccess()) {
      requester.setCardToken(cardTokenResponse.message);
      let response = await requester.pushToBackend();

      this.setState({ showLoadingIndicator: false }); //<-- below setTimeout can confirm this line run before them
      if (response.isSuccess()) {
        setTimeout(() => { this.navigator.backToPreviousScreen(); }, 800);
      } else {
        setTimeout(() => { Alert.alert('your purchase has error. Try again'); }, 800);
      }
    } else {
      this.setState({ showLoadingIndicator: false });
      setTimeout(() => { Alert.alert('cannot get your card token.'); }, 800);
    }
  }, 800);
};
步骤5-在将
showLoadingIndicator
设置为
false
之前,将弹出警报,从而停止设置,下面是遇到问题的代码:

  this.setState({ showLoadingIndicator: false });
  if (response.isSuccess()) {
  } else {
    setTimeout(() => { Alert.alert('your purchase has error. Try again'); }, 800);
  }

setState
函数的第二个可选参数是与状态更改同步运行的回调函数

因此,您可以依赖以下几点:

this.setState({
  //change state variables here
}, () => {
   //do the next work here...
});
回调函数总是在状态更改后运行

在您的代码中,这将起作用:

this.setState({ showLoadingIndicator: false }, () => {
  if (response.isSuccess()) {
      this.navigator.backToPreviousScreen();
  } else {
   Alert.alert('your purchase has error. Try again');
  }
});

希望这对你有帮助。愉快的编码:)

值得一提的是:不管应该返回什么,setState回调都会启动。因此,即使状态没有改变,setState回调也会启动。@suraj_malviya感谢您的回答。对于setState()函数之后的回调,我相信您的答案是正确的。但是,它仍然不能像使用setTimeout()那样工作。我不知道为什么…:(
它仍然不能像使用setTimeout()那样工作)
,@WingChoy您能更具体一点吗?您能更新您的问题吗?添加此信息、屏幕截图、您更改的代码,以便我们了解有关您问题的更多信息吗?警报在设置状态之前发出,使用您提到的代码。我想提到的一件事是,我的设置状态用于控制react-native模态组件v可视性。这会影响结果吗?@c-chavez当然,请稍候。我会做一些截图来解释清楚。
this.setState({
  //change state variables here
}, () => {
   //do the next work here...
});
this.setState({ showLoadingIndicator: false }, () => {
  if (response.isSuccess()) {
      this.navigator.backToPreviousScreen();
  } else {
   Alert.alert('your purchase has error. Try again');
  }
});