首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用async / await时,在执行下一个函数之前,React本机AsyncStorage不返回值

使用async / await时,在执行下一个函数之前,React本机AsyncStorage不返回值
EN

Stack Overflow用户
提问于 2018-06-06 01:52:50
回答 1查看 182关注 0票数 0

我正在做一个react原生项目,在这个项目中,用户会看到一个闪屏,闪屏会从AsyncStorage中读取,以检查用户是否是第一次使用该应用程序,如果是的话,他们会被引导到导览屏幕,之后,一旦他们按下继续按钮,就会转到主屏幕。当用户按下continue时,将设置一个键,并使用AsyncStorage (值为false的键firstUse )设置一个值。

现在,当我返回到应用程序时,导览页面再次加载。当我查看控制台日志时,我注意到在getSettings函数完成执行之前,checkFirstUse函数返回未定义的值(这些值在之后输出)。我假设getSettings首先运行,直到返回响应(因为函数使用async / await),但显然在解决这个问题上没有任何帮助。

以下是代码(为简单起见进行了简化)

SplashScreen:

@inject("settingsStore")
class SplashScreen extends Component {
  constructor(props: Object) {
    super(props);
  }

  componentDidMount() {
    this.props.settingsStore.getSettings();
    this.checkFirstUse();
  }

  checkFirstUse = () => {
    console.log(' is this first use '+this.props.settingsStore.settings.firstUse);
    if (this.props.settingsStore.settings.firstUse === 'false') {
      this.props.navigation.navigate('HomeScreen')
    }else {
      this.props.navigation.navigate('TourScreen')
    }
  }
  render() {
    return (
      <View>
        <Text>This is the SPLASH SCREEN</Text>
      </View>
    );
  }
}
export default SplashScreen;

SettingsStore:

export default class SettingsStore {
  @observable settings = [];

  @action async getSettings() {
    try{
      var response = await AsyncStorage.multiGet(['firstUse', 'userID']);
      this.settings.firstUse = response[0][1];
      this.settings.UserID = response[1][1];
      console.log('got settings'); 
      console.log(response);    
    } catch (error) {
      console.log(error.message);
    }
  }

  @action async setFirstUse() {
    try {
      await AsyncStorage.setItem('firstUse', 'false');
      this.settings.firstUse = 'false';
      console.log('Have set first use');
    } catch (error) {
      console.log(error.message);
    }
  }
}

提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2018-06-06 08:23:38

因此,我在SplashScreen中更新了代码:

async componentDidMount() {
  await this.props.settingsStore.getSettings();
  await this.checkFirstUse();
}

这似乎是工作,我将进一步测试,并报告。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50706174

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档