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

111*_*110 0 reactjs react-native react-redux asyncstorage

我有App.js文件,它是我的应用程序的根目录(ios和android都对其引用)。
在调用render方法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 (...
Run Code Online (Sandbox Code Playgroud)

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

dho*_*lik 6

尝试以下方法:

...

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')
    ...
}

...
Run Code Online (Sandbox Code Playgroud)

事情是init()返回一个承诺,您需要等到它解决。那是时候await进行救援了。

您还需要设置一些加载器,该加载器将在首次渲染时存在,并在获取AsyncStorage值后切换状态以将其替换为实际标记。我已将其放入代码中,但是根据您的设置,您可能想触发redux操作。