在整个应用程序加载之前,从Asyncstorage获得价值的最佳方法是什么



我有App.js文件,它是我应用程序的根(iOS和Android引用)。
我有一个在AsyncStorage中所需的值,在app.js渲染方法之前需要。
问题是因为它是 async,我无法获得该值。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.init()
  }
  async init() {
     try {
  const value = await AsyncStorage.getItem('@myPoorValue:key');
  if (value !== null){
    ...
  }
} catch (error) {}
  }
}
...
render (...

我希望我在这里解释了我的问题。
我知道没有办法同步(我想要),但在这种情况下不知道该怎么办。
为了更好地解释它,我使用I18n,然后手动将I18n.locale设置为某些值,而其他组件在我手动设置之前获取默认值。
只是要注意我也使用redux,然后将选定的值传递给它。

尝试以下内容:

...
constructor(props) {
  super(props)
  
  this state = {
    isLoading: true
  }
}
  
async componentDidMount() {
  await this.init()
  
  // you might want to do the I18N setup here
  this.setState({ 
    isLoading: false
  })
}
async init() {
    const value = await AsyncStorage.getItem('@myPoorValue:key')
    ...
}
...

问题是init()返回承诺,您需要等到它得到解决。那是await来营救的时候。

您还需要设置一些将在第一个渲染上存在的加载程序,并在获取异步值之后切换状态以替换为实际标记。我将其放入代码中,但是您可能需要触发Redux操作,具体取决于您的设置。

最新更新