小编典典

使用异步componentDidMount()好吗?

reactjs

componentDidMount()在React Native中用作异步函数是一种好习惯还是应该避免呢?

我需要从AsyncStorage安装组件时获取一些信息,但是我知道使之成为可能的唯一方法是使componentDidMount()函数异步。

async componentDidMount() {
    let auth = await this.getAuth();
    if (auth) 
        this.checkAuth(auth);
}

这有什么问题吗,还有其他解决方案吗?


阅读 805

收藏
2020-07-22

共1个答案

小编典典

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

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

// This is typescript code
componentDidMount(): void { /* do something */ }

async componentDidMount(): Promise<void> {
    /* do something */
    /* You can use "await" here */
}

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

  1. async关键字:在打字稿,这仅仅是一个代码标记。它做两件事:
    • 强制将返回类型Promise<void>改为void。如果您明确指定返回类型为非承诺(例如:void),则打字稿将向您吐一个错误。
    • 允许您await在方法内部使用关键字。
  2. 返回类型从更改voidPromise<void>

    • 这意味着您现在可以执行以下操作:
      async someMethod(): Promise<void> { await componentDidMount(); }
  3. 现在,您可以await在方法内部使用关键字,并暂时暂停其执行。像这样:

    async componentDidMount(): Promise<void> {
    const users = await axios.get<string>("http://localhost:9001/users");
    const questions = await axios.get<string>("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<void>也是无害的。

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

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

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

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

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

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

2020-07-22