在本机导航中使用 AsyncStorage 时,initialRouteName 未正确使用

问题描述

我需要根据本机导航中的 AsyncStorage 值进行导航。但即使我在 AsyncStorage 中有值,它也总是将我带到登录页面。

在我迄今为止尝试过的下面,

    function App(props) {
  const [storeId,setStoreId] = useState(null);

  AsyncStorage.getItem(STORAGE_KEYS.LOCATION_ID).then((id) => {
    setStoreId(id);
  });

  const initialRoute = storeId && 'NfcScreen';
  return (
    <Provider store={store}>
      <NavigationContainer>
        <Stack.Navigator
          initialRouteName={initialRoute}
          screenOptions={!isTablet ? styles : ''}>
          {isTablet && (
            <Stack.Screen
              options={{headerShown: false}}
              name={appPages.locationIdentification}
              component={Locationidentification}
            />
          )}
          <Stack.Screen
            name={appPages.nfc}
            component={NfcPage}
            options={{headerShown: false}}
          />
  </Stack.Navigator>
      </NavigationContainer>
    </Provider>

我注意到第一个状态返回 null 然后它返回 asyncstorage 值。因为状态更新缓慢,所以 locationIdentification 页面被渲染。有什么办法可以试试吗??

帮助将是非常可观的。谢谢:)

解决方法

每个 setState 操作都会重新渲染页面,因此您需要访问最新状态。 我认为你应该把你的 AsynacStorage 代码放在一个 usseEffect 中并将 initialRouteName 值定义为一个函数

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...