React Native Redux Firebase 身份验证导航重定向

问题描述 投票:0回答:0

我正在使用 redux 和 firebase 来验证用户。

Authslice:

const initialState = {
  user: null,
};

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    setUser: (state, action) => {
      state.user = action.payload;
    },
  },
});
export const selectCurrentUser = (state) => state.auth.user;

授权服务:

const signUpWithEmailService = async (fullName, email, password) => {
  const result = await createUserWithEmailAndPassword(
    auth,
    email,
    password
  ).then((userCredentials) => {
    // Get the user's UID
    const uid = userCredentials.user.uid;

    // Create a new object with the UID and any additional properties
    const newUser = {
      firebaseUID: uid,
      name: fullName,
    };

    axios
      .post("http://localhost:8080/api/v1/users", newUser, {
        headers: {
          "Content-Type": "application/json",
        },
      })
      .then((response) => {
        // Handle the response from the API
      });

    // Send email verification
    sendEmailVerification(userCredentials.user);
  });
  return result;
};

导航:

const RootNavigation = () => {
  const dispatch = useDispatch();
  const currentUser = useSelector(selectCurrentUser);
  console.log(currentUser);
  const colorScheme = useColorScheme();

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      dispatch(setCurrentUser(user));
    });
    return unsubscribe;
  }, []);

  return (
    <NavigationContainer
      theme={colorScheme === "dark" ? AppLightTheme : AppDarkTheme}
    >
      {currentUser ? <UserStack currentUser={currentUser} /> : <AuthStack />}
    </NavigationContainer>
  );
};

export default RootNavigation;

const UserStack = ({ currentUser }) => {
  const Stack = createNativeStackNavigator();
  return (
    <SafeAreaProvider>
      <Stack.Navigator>
        {currentUser?.emailVerified ? (
          <Stack.Screen
            name="HomeScreen"
            component={HomeScreen}
            options={{ headerShown: false }}
          />
        ) : (
          <Stack.Screen
            name="VerifyEmailScreen"
            component={VerifyEmailScreen}
            options={{ headerShown: false }}
          />
        )}
      </Stack.Navigator>
    </SafeAreaProvider>
  );
};

export default UserStack;

我有一个问题,我没有使用 useSelector 根据用户状态自动定向到 VerifyEmailScreen,我相信问题是我对 redux 的理解和组件重新加载的状态。我可以看到使用 console.log 定义的用户对象具有正确的详细信息。

react-native redux firebase-authentication react-native-navigation
© www.soinside.com 2019 - 2024. All rights reserved.