我正在构建登录系统。当我使用选择器函数时,我遇到了存储状态值的问题。在我的系统中,我想从存储状态值中获取isSuccess、error和userInfo
第一个月
const userLogin = useSelector((state) => state.userLogin);
console.log(userLogin);
const { isSuccess, error, userInfo } = userLogin;
如果错误,则会在UI上显示错误消息,否则,如果isSuccess,则会显示成功消息。isSuccess在发布到API成功时出现(表示用户登录成功),且用户数据被分派到loginSuccess减少,否则分派到loginFail的错误值减少/action/userAction.js
import {
loginSuccess,
loginFail,
} from "\~/redux/user/userLoginSlice";
export const login = (inputs) =\> async (dispatch) =\> {
try {
const {data} = await request.post("/auth/login", inputs);
dispatch(loginSuccess(data));
localStorage.setItem("userInfo", JSON.stringify(data));
} catch (error) {
console.log(error.response.data)
dispatch(loginFail(error.response.data))
}
.然而,在loginSucces reduce中不仅获得isSuccess,而且在上次登录为loginFail console.log(userLogin)时也会获得错误。它应该只显示userInfo和isSuccess。任何人都可以帮助我解决这个问题。这是reduceuserLoginSlice.js
import { createSlice } from '@reduxjs/toolkit';
const userLoginSlice = createSlice({
name: 'userInfo',
initialState: {},
reducers: {
loginSuccess: (state, action) => {
state.isSuccess = true;
state.userInfo = action.payload;
},
loginFail: (state, action) => {
state.error = action.payload
},
},
});
export const { loginSuccess, loginFail } = userLoginSlice.actions;
export default userLoginSlice.reducer;
还有我的折扣店store.js
import { configureStore } from '@reduxjs/toolkit';
import productModalReducer from './product-modal/productModalSlice';
import cartItemsSlice from './cart/cartSlide';
import userLoginSlice from './user/userLoginSlice.js';
import userRegisterSlice from './user/userRegisterSlice.js';
import userUpdateSlice from './user/userUpdateSlice.js';
const userInfoFromStorage = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : null;
const initialState = {
userLogin: { userInfo: userInfoFromStorage },
};
export const store = configureStore({
reducer: {
productModal: productModalReducer,
cartItems: cartItemsSlice,
userLogin: userLoginSlice,
userRegister: userRegisterSlice,
userUpdate: userUpdateSlice,
},
preloadedState: initialState,
});
在redux中,当分派到另一个时,状态值不变
1条答案
按热度按时间4ktjp1zp1#
看起来这可能是因为
loginSuccess
仅将userInfo
和isSuccess
添加到状态中,而没有省略先前的error
。也许可以尝试重置状态值以排除减速器中的
error
:或者返回一个状态值而不使用Immer代理状态: