使用异步componentDidMount()好吗? [英] Is using async componentDidMount() good?

查看:118
本文介绍了使用异步componentDidMount()好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is using componentDidMount() as an async function good practice in React Native or should I avoid it?

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

I need to get some info from AsyncStorage when the component mounts, but the only way I know to make that possible is to make the componentDidMount() function async.

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

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

Is there any problem with that and are there any other solutions to this problem?

推荐答案

让我们首先指出差异并确定差异可能引起的麻烦.

Let's start by pointing out the differences and determining how it could cause troubles.

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

Here is the code of async and "sync" componentDidMount() life-cycle method:

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

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

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

By looking at the code, I can point out the following differences:

  1. async关键字:在打字稿中,这仅仅是一个代码标记.它做两件事:
    • 强制返回类型为Promise<void>而不是void.如果您明确指定返回类型为非承诺(例如:void),则打字稿会向您吐一个错误.
    • 允许您在方法内使用await关键字.
  1. The async keywords: In typescript, this is merely a code marker. It does 2 things:
    • Force the return type to be Promise<void> instead of void. If you explicitly specify the return type to be non-promise (ex: void), typescript will spit an error at you.
    • Allow you to use await keywords inside the method.
  • 这意味着您现在可以执行以下操作:
    async someMethod(): Promise<void> { await componentDidMount(); }
  • It means you can now do this:
    async someMethod(): Promise<void> { await componentDidMount(); }

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

You can now use await keyword inside the method and temporarily pause its execution. Like this:

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();
}

现在,它们怎么会引起麻烦?

Now, how could they cause troubles?

  1. async关键字绝对无害.
  2. 我无法想象需要调用componentDidMount()方法的任何情况,因此返回类型Promise<void>也是无害的.

  1. The async keyword is absolutely harmless.
  2. I cannot imagine any situation in which you need to make a call to the componentDidMount() method so the return type Promise<void> is harmless too.

调用返回类型为Promise<void>且没有await关键字的方法与调用返回类型为void的方法没有区别.

Calling to a method having return type of Promise<void> without await keyword will make no difference from calling one having return type of void.

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

Since there is no life-cycle methods after componentDidMount() delaying its execution seems pretty safe. But there is a gotcha.

比方说,上面的this.setState({users, questions});将在10秒后执行.在延迟时间的中间,另一个...

Let's say, the above this.setState({users, questions}); would be executed after 10 seconds. In the middle of the delaying time, another ...

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

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

... were successfully executed and the DOM were updated. The result were visible to users. The clock continued ticking and 10 seconds elapsed. The delayed this.setState(...) would then execute and the DOM would be updated again, that time with old users and old questions. The result would also be visible to users.

=>将asynccomponentDidMount()方法一起使用是非常安全的(不确定100%).我是它的忠实拥护者,到目前为止,我还没有遇到任何让我头疼的问题.

=> It is pretty safe (I'm not sure about 100%) to use async with componentDidMount() method. I'm a big fan of it and so far I haven't encountered any issues which give me too much headache.

这篇关于使用异步componentDidMount()好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆