【问题标题】:React Native AsyncStorage not returning values before the next function is executed when using async / await使用 async / await 时,React Native AsyncStorage 在执行下一个函数之前不返回值
【发布时间】:2018-06-05 17:52:49
【问题描述】:

我正在开发一个 react native 项目,在该项目中向用户显示初始屏幕,并且初始屏幕从 AsyncStorage 读取,以检查这是否是用户第一次使用该应用程序,如果是,他们会被定向到游览屏幕之后,一旦按下继续按钮,他们就会进入主屏幕。当用户按下继续键时,会设置一个键并使用 AsyncStorage 设置一个值(key firstUse,值为 false)。

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

这里是代码(为了简单起见)

闪屏:

@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;

设置商店:

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

提前致谢。

【问题讨论】:

    标签: reactjs asynchronous async-await native asyncstorage


    【解决方案1】:

    所以我在 SplashScreen 中更新了我的代码:

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

    这似乎有效,我将进一步测试并报告。

    【讨论】:

      猜你喜欢
      • 2018-10-28
      • 2020-01-31
      • 1970-01-01
      • 2020-04-06
      • 2018-03-27
      • 2021-12-13
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      相关资源
      最近更新 更多