首页 > 解决方案 > 在构造函数中调用具有 await 关键字的函数?

问题描述

class AuthLoadingScreen extends React.Component {
  constructor(props) {
    super(props);
    this._bootstrapAsync();
  }

  // Fetch the token from storage then navigate to our appropriate place
  _bootstrapAsync = async () => {
    const userToken = await AsyncStorage.getItem('userToken');

    // This will switch to the App screen or Auth screen and this loading
    // screen will be unmounted and thrown away.
    this.props.navigation.navigate(userToken ? 'App' : 'Auth');
  };

  // Render any loading content that you like here
  render() {
    return (
      <View>
        <ActivityIndicator />
        <StatusBar barStyle="default" />
      </View>
    );
  }
}

我知道 await 将等待执行,直到承诺解决。在这里,我们在构造函数中调用具有 await 关键字的 bootstrapAsync 函数,这是否意味着构造函数执行将等到 promise 解决?

标签: javascriptreact-nativereact-navigation

解决方案


您使用的是,它是一个使用SwitchStackNavigatorAuthLoader的“切换加载器组件” 。这是一个您希望在其中花费尽可能少的时间的屏幕。

为什么?好吧,因为除了无限的进度条之外没有要显示的内容。这就是在构造函数中调用 bootstrap async 的原因。

构造函数执行将等到承诺解决?

不,不会的。切换加载器的想法是加载应用程序的当前状态并将(又名switch)重定向到正确的路线。

这就是为什么屏幕是否挂载都没有关系的原因,这就是为什么在构造函数中调用 bootstrapAsync 的原因,因为这是最早可以调用它的原因。


推荐阅读