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

What is a best way to get value from AsyncStorage before whole app load

我有 App.js 文件,它是我的应用程序的根目录(ios 和 android 都引用了它)。
在调用 app.js 渲染方法之前,我在 AsyncStorage 中保留了一个值。
问题是 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() returns 一个承诺,您需要等到它得到解决。这就是 await 来救援的时候了。

您还需要设置一些将在第一次渲染时出现的加载程序,并在获取 AsyncStorage 值后切换状态以将其替换为实际标记。我已将其放入代码中,但您可能想要触发 redux 操作,具体取决于您的设置。