componentDidMount()在React Native中用作异步函数是一种好习惯还是应该避免呢?
componentDidMount()
我需要从AsyncStorage安装组件时获取一些信息,但是我知道使之成为可能的唯一方法是使componentDidMount()函数异步。
AsyncStorage
async componentDidMount() { let auth = await this.getAuth(); if (auth) this.checkAuth(auth); }
这有什么问题吗,还有其他解决方案吗?
让我们首先指出差异并确定差异可能如何引起麻烦。
这是异步和“同步” componentDidMount()生命周期方法的代码:
// This is typescript code componentDidMount(): void { /* do something */ } async componentDidMount(): Promise<void> { /* do something */ /* You can use "await" here */ }
通过查看代码,我可以指出以下差异:
async
Promise<void>
void
await
返回类型从更改void为Promise<void>
async someMethod(): Promise<void> { await componentDidMount(); }
现在,您可以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();
}
现在,它们怎么会引起麻烦?
调用到具有方法的返回类型的Promise<void>无await关键字将没有从调用具有返回类型的一个区别void。
假设上述操作this.setState({users, questions});将在10秒后执行。在延迟的时间中间,另一个…
this.setState({users, questions});
this.setState({users: newerUsers, questions: newerQuestions});
…已成功执行,并且DOM已更新。结果对用户可见。时钟继续滴答作响,经过了10秒钟。this.setState(...)然后,将执行延迟的操作,然后再次使用旧用户和旧问题更新DOM。结果也将对用户可见。
this.setState(...)
= > async与componentDidMount()method 一起使用非常安全(我不确定大约100%)。我非常喜欢它,到目前为止,我还没有遇到任何让我头疼的问题。