简体   繁体   English

反应setstate不渲染,直到回调完成

[英]react setstate not rendering until callback finishes

I am trying to change button to saving state while I run code to get information. 我试图在运行代码以获取信息时将按钮更改为保存状态。

I have this.setState({ saving: true }, () => this.save(event) }) 我有this.setState({ saving: true }, () => this.save(event) })

In this.save I have a rest call. this.save我有一个休息电话。 I can see from the log that the state is updated but visually on the site the button does not go into the spinning circle like it should with that updated value. 我从日志中可以看到状态已更新,但是在网站上直观地看到该按钮并没有像旋转时那样具有更新的值。

Is there a way to force update rendering before running the callback function or a better method to set a button to saving while I do a remote call that could take a little bit of time? 有没有办法在运行回调函数之前强制更新渲染,或者有更好的方法来设置按钮以进行保存,而我进行远程调用可能会花费一些时间?

There is no reason to force this. 没有理由强制这样做。 Change your state in parallel to the actual saving: 与实际保存同时更改状态:

<button onClick={() => this.save()}>save</button>

paired with: 搭配:

save() {
  this.setState({ saving: true });
  remoteAPI.save({ 
    data: this.getSaveData(),
    credentials: this.getCredentials()
    ...
  }, response => {
    this.setState({ saving: false });
    if(response.error) {
      // ohnoes!
    } else {
      // nice.
    }
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM