登录时设置 userId 时出现 Redux 问题

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

我正在尝试react redux,我被困在这里,所以实际上当我点击登录时,我将 data.userid 存储到reducer,并且在预订时我试图访问用户id,但不幸的是我得到了null,我希望有人回答这个问题以解释的方式。我觉得我可以存储 下面是我的代码。

登录.js

import { useDispatch } from 'react-redux'; // Import useDispatch
import Link from 'next/link';
import { login } from '../utils/api';
import { setUserId } from '../redux/slices/authSlice'; 

const handleLogin = async (event) => {
        event.preventDefault();

        try {
            if (!username || !password) {
                alert('Please enter username and password');
                return;
            }
            const response = await login(username, password);
            const data = await response.json();

            dispatch(setUserId(data.userId));

            window.location.href = '/';
        } catch (error) {
            console.error('Login failed:', error);
            // Handle login failure (display error message, etc.)
        }
    };

authSlice.js

import { createSlice } from '@reduxjs/toolkit';

const initialState = {
    userId: null,
    isAuthenticated: false,
};

const authSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
        setUserId(state, action) {
            state.userId = action.payload;
            state.isAuthenticated = true;
        },
        logout(state) {
            state.userId = null;
            state.isAuthenticated = false;
        },
    },
});

export const { setUserId, logout } = authSlice.actions;

export const selectUserId = (state) => state.auth.userId;
export default authSlice.reducer;

预订.js

mport { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { useSelector, useDispatch } from 'react-redux'; // Import useDispatch and useSelector
import { fetchSlotById, confirmBooking } from '../../utils/api';

const Booking = () => {
    const availableSlots = useSelector((state) => state.slots);
    const [selectedSlot, setSelectedSlot] = useState(null);
     const userId = useSelector((state) => state.auth.userId);
    const router = useRouter();
    const { id } = router.query;
    const dispatch = useDispatch();
    console.log(userId, 'booking'); // Here im getting userId as null
reactjs react-redux redux-toolkit next.js13
1个回答
0
投票

发现两个问题:

成功获取数据并调度后,页面会重新加载,导致Redux中存储的所有数据因页面刷新而为空。 分派后,必须确保所有 Redux 提供程序都持久存在。

要解决这些问题:

实现 Redux persistence 以在页面重新加载时保留数据。 探索替代方法来避免页面重新加载,确保数据保持完整而无需刷新页面。

© www.soinside.com 2019 - 2024. All rights reserved.