首页 > 解决方案 > 当组件离开视图时如何使用异步等待

问题描述

如何使用异步等待?

当调用 this.props.onChangeStep1() 时,渲染视图的组件被另一个组件替换。

如果组件已被交换,Async Await 是否仍然有效?

s3.upload(params, function(err, data) {

this.props.onChangeStep1(); //<----- After s3.upload I want to call this first 

            this.setState(   //<----But I want this to run in the background 
                                  // even though the component is not in view
                  {
                myState: "data-from-s3Upload"
              });
          }.bind(this)
        );

标签: reactjsasynchronousasync-await

解决方案


如果回调设置为稍后执行,并且启动异步调用的组件已卸载,则无论如何都会执行回调。如果回调尝试对未安装的组件进行操作(例如更改其状态),它将被视为内存泄漏,React 将在控制台中通过错误消息通知您。


推荐阅读