【问题标题】:initialRouteName is not taking correctly by using AsyncStorage in react native Navigation在反应本机导航中使用 AsyncStorage 未正确使用 initialRouteName
【发布时间】:2021-04-28 08:36:06
【问题描述】:

我需要根据 react-native 导航中的 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 页面会被渲染。有什么办法可以试试吗?

帮助将非常明显。谢谢:)

【问题讨论】:

    标签: react-native react-native-android react-native-navigation


    【解决方案1】:

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

    更新: 也许已经晚了,但你可以使用导航监听器

    【讨论】:

    • 我做了同样的事情,但没有解决问题@Jamal :(
    • 顾名思义,AsyncStorage 有一个小的延迟,因为你在路由后更新状态,你应该保持它直到状态更新
    猜你喜欢
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 2021-04-27
    • 2017-01-13
    • 1970-01-01
    相关资源
    最近更新 更多