【问题标题】:Wait for initialization of lazy loaded state等待延迟加载状态的初始化
【发布时间】:2018-04-09 14:05:42
【问题描述】:

我有一个按钮和一个onClick 处理程序。我在onClick 处理程序中做的第一个想法是

if (this.state.lazyLoadedData === undefined) {
    await this.loadData();
}

我的问题是,如果我快速单击按钮两次,this.loadData() get 会执行两次。

解决这个问题的 typescript/react 惯用方法是什么?

【问题讨论】:

    标签: javascript reactjs typescript asynchronous async-await


    【解决方案1】:

    惯用的方法是始终使用显式承诺来访问延迟加载的数据。

    在某处声明并初始化它

    loadDataPromise: Promise<YourDataType> | undefined = undefined;
    

    然后,在 onclick 处理程序中

    if (!this.loadDataPromise) {
        this.loadDataPromise = this.loadData();
    }
    
    this.loadDataPromise.then(yourDataHere => {
    });
    

    【讨论】:

    • loadDataPromise 应该住在哪里?此代码是反应组件的一部分。如果它处于组件状态,那么我认为 loadDataPromise 实际上应该看起来像 this.setState({ loadDataPromise: this.loadData() })setState 本身是异步的,所以仍然存在问题,不是吗?如果我把它作为一个普通的成员变量,那安全吗?不是有时会重新创建组件吗?在这种情况下,loadDataPromise 变量不会丢失吗?
    • 嗯.. 阅读here。也许让“this”保持loadDataPromise是安全的?
    • 是的,将它放在组件中应该是安全的,在构造函数中初始化。不确定 React,但如果它在构造函数中使用 undefined 初始化,我认为即使重新创建组件它也会工作。
    • 我去了,但是yourDataHere = await this.loadDataPromise;谢谢!
    猜你喜欢
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    相关资源
    最近更新 更多