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

查看:21
本文介绍了使用异步 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.如果您明确指定返回类型为 non-promise(例如:void),typescript 会向您吐出错误.
    • 允许您在方法中使用 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{ 等待 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();
}

现在,他们怎么会造成麻烦?

  1. async 关键字绝对无害.
  2. 我无法想象您需要调用 componentDidMount() 方法以便返回类型 Promise 也无害的任何情况.

  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 的方法而没有 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天全站免登陆