热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

使用异步componentDidMount()好吗?

使用异步componentDid

让我们首先指出差异并确定差异可能如何引起麻烦。

这是异步和“同步” componentDidmount()生命周期方法的代码:

// This is typescript code
componentDidmount(): void { /* do something */ }
async componentDidmount(): Promise {
/* do something */
/* You can use "await" here */
}

通过查看代码,我可以指出以下差异:


  1. async关键字:在打字稿,这仅仅是一个代码标记。它做两件事:

    • 强制将返回类型Promise改为void。如果您明确指定返回类型为非承诺(例如:void),则打字稿将向您吐一个错误。

    • 允许您await在方法内部使用关键字。



  2. 返回类型从更改voidPromise


    • 这意味着您现在可以执行以下操作:async someMethod(): Promise { await componentDidmount(); }



  3. 现在,您可以await在方法内部使用关键字,并暂时暂停其执行。像这样:

    async componentDidmount(): Promise {
    const users = await axios.get("http://localhost:9001/users");
    const questiOns= await axios.get("http://localhost:9001/questions");
    // Sleep for 10 seconds
    await new Promise(resolve => { setTimeout(resolve, 10000); });
    // This line of code will be executed after 10+ seconds
    this.setState({users, questions});
    return Promise.resolve();

    }




  1. async关键字是绝对无害的。

  2. 我无法想象在任何情况下都需要调用该componentDidmount()方法,因此返回类型Promise也是无害的。

调用到具有方法的返回类型的Promiseawait关键字将没有从调用具有返回类型的一个区别void


  1. 由于没有生命周期方法,因此componentDidmount()延迟执行似乎很安全。但是有一个陷阱。

假设上述操作this.setState({users, questions});将在10秒后执行。在延迟的时间中间,另一个…

this.setState({users: newerUsers, questions: newerQuestions});

…已成功执行,并且DOM已更新。结果对用户可见。时钟继续滴答作响,经过了10秒钟。this.setState(...)然后,将执行延迟的操作,然后再次使用旧用户和旧问题更新DOM。结果也将对用户可见。

= > asynccomponentDidmount()method
一起使用非常安全(我不确定大约100%)。我非常喜欢它,到目前为止,我还没有遇到任何让我头疼的问题。





推荐阅读
author-avatar
拍友2502875873
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有