我在使用redux工具包的MERN身份验证系统中遇到问题



我正试图用redux工具包创建身份验证系统,一切看起来都很好,但当我进行条件呈现时,它在开始时无法正常工作。当前用户作为初始状态为null,但直到它呈现不同的组件,只有当存在当前用户时才应该呈现

下面是我的代码

  1. 验证切片

import { createSlice } from "@reduxjs/toolkit";
// Get currentUser from localstorage
// const currentUser = JSON.parse(localStorage.getItem('currentUser'));
// currentUser ? currentUser :
const authSlice = createSlice({
name: "auth", // Global state
initialState: {
currentUser: null,
isFetching: false,
error: false,
},
reducers: {
// All the reducer
// Reset To initial state
reset: (state) => {
state.currentUser = null;
state.isFetching = false;
state.error = false;
},
// Login Reducers
loginStart: (state) => {
state.isFetching = true;
},
loginSuccess: (state, action) => {
state.isFetching = false;
state.currentUser = action.payload;
},
loginFail: (state) => {
state.isFetching = false;
state.error = true;
},
// Register Reducers
registerStart: (state) => {
state.isFetching = true;
},
registerSuccess: (state, action) => {
state.isFetching = false;
state.currentUser = action.payload;
},
registerFail: (state) => {
state.isFetching = false;
state.error = true;
},
// Logout
logoutSuccess: (state) => {
(state.currentUser = null),
(state.isFetching = false),
(state.error = false);
},
},
});
export const {
reset,
loginStart,
loginSuccess,
loginFail,
registerStart,
registerSuccess,
registerFail,
} = authSlice.actions;
export default authSlice.reducer;

  1. 存储

import { configureStore } from "@reduxjs/toolkit";
import authReducer from './authRedux'
import storage from 'redux-persist/lib/storage'
import { 
persistReducer,
persistStore,
FLUSH,
REHYDRATE,
REGISTER,
PURGE,
PERSIST } from 'redux-persist';
const persistConfig={
key:'root',
version: 1,
storage,
}
const persistedReducer = persistReducer(persistConfig, authReducer);
export const store = configureStore({
reducer:{
auth: persistedReducer,
},
middleware:(getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck:{
ignoreActions:[FLUSH,REGISTER,REHYDRATE,PERSIST,PURGE],
},
})
});
export let persistor = persistStore(store);

  1. 登录

import React, { useState } from "react";
import { Form, Card, Button, Alert } from "react-bootstrap";
import { Link, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { login } from "../../Redux/apiCalls";
import UpdateProfile from "../UpdateProfile/Updateprofile";
export default function Login() {
const [username, setUserName] = useState("");
const [password, setPassword] = useState("");
const dispatch = useDispatch();
const currentUser = useSelector((state) => state.auth);
const { isFetching, error } = useSelector((state) => state.auth);
const navigate = useNavigate();
async function handleSubmit(e) {
e.preventDefault();
try {
if(!currentUser){
navigate('/')
}else{
login(dispatch, { username, password });
navigate('/');
}
} catch (error) {
console.log(error);
}
}
console.log(currentUser);
return (
<>
{currentUser ? (<UpdateProfile/>):(
<Card className="shadow-lg p-3 mb-2 bg-white rounded">
<Card.Body>
<h2 className="text-center mb-4">Log In</h2>
{error && <Alert variant="danger">{error}</Alert>}
<Form onSubmit={handleSubmit}>
<Form.Group id="username">
<Form.Label>UserName</Form.Label>
<Form.Control
type="text"
required
onChange={(e) => setUserName(e.target.value)}
/>
</Form.Group>
<Form.Group id="password">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
required
onChange={(e) => setPassword(e.target.value)}
/>
</Form.Group>
<Button
disabled={isFetching}
className="w-100 mt-4 mb-4"
type="submit"
>
Log In
</Button>
</Form>
<div className="w-100 text-center mt-2">
<Link to="/forgot-password">Forgot Password</Link>
</div>
<div className="w-100 text-center mt-3">
Need an Account? <Link to="/signup">Sing Up</Link>
</div>
</Card.Body>
</Card>
)}

</>
);
}

正如在一开始的登录组件中一样,它应该呈现登录页面,因为没有用户,但它呈现更新配置文件,即使在我的redux开发工具中,它也显示当前用户为空

快速浏览后,我会在登录中检查以下内容:

async function handleSubmit(e) {
e.preventDefault();
try {
if(!currentUser){
navigate('/')
} else {
login(dispatch, { username, password });
navigate('/');
}
} catch (error) {
console.log(error);
}
}

我认为你的调度功能应该看起来像:

dispatch(login({ username, password }));

这是假设您的登录函数接受一个对象并希望被传递用户名和密码。我不熟悉redux-persistent,所以如果我错过了该包的特定内容,请道歉。

我解决了它,我只是在使用选择器析构函数方法中进行了更改

从这个

const currentUser = useSelector((state) => state.auth);

到此

const currentUser = useSelector((state) => state.auth.currentUser);

相关内容

最新更新