显示一次登录屏幕



有人知道我在哪里出错了吗?当用户点击调用onSkip函数的按钮时,我试图调度一个动作,在reducer中,我将项目设置为本地存储,并在rootstack组件中检索它,因此我可以有条件地设置堆栈导航器中的初始屏幕。它总是返回false并进入登录屏幕而不是登录屏幕。

import React, { useEffect } from 'react'
import { NavigationContainer } from '@react-navigation/native'
import { createNativeStackNavigator } from '@react-navigation/native-stack'
import { RootStackParamList } from '../interfaces/RootStackParamList'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { theme } from '../themes/themes'
import { useAppSelector } from '../app/hooks'
import DrawerNav from './DrawerNav'
import Tabs from './Tabs'
import HomeScreen from '../screens/HomeScreen'
import Login from '../screens/Auth/Login'
import OnboardingScreen from '../screens/Onboarding/OnboardingScreen'
import OtpScreen from '../screens/Auth/OtpScreen'
function RootStack() {
const Stack = createNativeStackNavigator<RootStackParamList>()
const onboardingState = useAppSelector(
(state) => state.onboarding.viewedOnBoarding
)
const [onboarded, setOnboarded] = React.useState(false)
const checkOnboarding = async () => {
try {
const value = await AsyncStorage.getItem('@onBoarding')
if (value !== null) {
setOnboarded(true)
}
} catch (err) {
} finally {
}
}
useEffect(() => {
checkOnboarding()
}, [])
return (
<NavigationContainer>
<Stack.Navigator
initialRouteName={
onboarded === true ? 'Login' : 'OnboardingScreen'
}
screenOptions={{
headerShown: false,
}}
>
<Stack.Screen options={{}} name='Login' component={Login} />
<Stack.Screen
name='OnboardingScreen'
component={OnboardingScreen}
/>
<Stack.Screen name='Tabs' component={Tabs} />
<Stack.Screen name='DrawerNav' component={DrawerNav} />
<Stack.Screen
name='OtpScreen'
component={OtpScreen}
options={{
title: 'OTP',
headerShown: true,
headerStyle: {
backgroundColor: theme.colors.whiteSmoke,
},
}}
/>
</Stack.Navigator>
</NavigationContainer>
)
}
export default RootStack 
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import AsyncStorage from '@react-native-async-storage/async-storage'
export interface onboardingState {
viewedOnBoarding: boolean
}
const initialState: onboardingState = {
viewedOnBoarding: false,
}
export const onboardingSlice = createSlice({
name: 'onboarding',
initialState,
reducers: {
setOnboardingAsync: (state, action: PayloadAction<boolean>) => {
state.viewedOnBoarding = action.payload
AsyncStorage.setItem('@onBoarding', JSON.stringify(action.payload))
},
},
})
// Action creators are generated for each case reducer function
export const { setOnboardingAsync } = onboardingSlice.actions
export default onboardingSlice.reducer
onSkip={() => (
dispatch(setOnboardingAsync(true)),
navigation.replace('Login'),
AsyncStorage.setItem('@onBoarding', JSON.stringify(true))
)}

如果你想持久化用户的登录状态,只需在你的项目中使用Redux-persist(不需要直接使用AsyncStorage)

在您实现了redux-persist之后,只需使用

const onboardingState = useAppSelector((state) => state.onboarding.viewedOnBoarding)

检查用户是否已登录。

相关内容

  • 没有找到相关文章

最新更新