问题描述
我需要根据本机导航中的 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 值定义为一个函数