首页 > 解决方案 > React-Native 等待 AsyncStorage.getItem()

问题描述

我面临的问题与以下链接中提到的完全一样:

https://github.com/facebook/react-native/issues/8589

希望从 AsyncStorage 加载并设置一些全局变量。因为其余页面取决于这些变量。

如果我使用async awaitthen()在设置全局变量之前,我仍然无法阻止其余页面呈现。

我试图让每个组件async,但不幸的是我无法让它正常工作。

主要是因为这一行:

const _App = (props) => {
  return (
    <I18nextProvider i18n={i18next}>
        <App />
    </I18nextProvider>);
}

// registerComponent() can't accept anything that is Async
AppRegistry.registerComponent(appName, () => _App);

标签: react-nativeasyncstorage

解决方案


尝试这个

const _App = (props) => {
  const [loaded, setLoaded] = useState(false)

  useEffect(()=>{

    const functionName = async () => {
      await registerComponent()
      setLoaded(true)
    }

    functionName()
  },[])

  if(!loaded) return <View><Text>Some Fancy loading stuff here</Text></View>

    return (
      <I18nextProvider i18n={i18next}>
          <App />
      </I18nextProvider>);
  }


推荐阅读