Auth.js
import { createSlice } from "@reduxjs/toolkit";
export const authSlice = createSlice({
name: "auth",
initialState: {
isAuthenticated: false,
user: {},
},
reducers: {
setUser: (state, { payload }) => {
state.user = payload.user;
state.isAuthenticated = true;
},
logout: (state) => {
state.user = {};
state.isAuthenticated = false;
},
},
});
export const { setUser, logout } = authSlice.actions;
export default authSlice.reducer;
index.js(商店)
import { configureStore } from "@reduxjs/toolkit";
import authReducer from "./auth.js";
export default configureStore({
reducer: {
auth: authReducer,
},
});
交易表单.js
const { categories } = useSelector((state) => state.auth.user);
**当我登录时出现了一个错误,但在重新加载页面时,错误就消失了。如何修复错误**
如果你没有登录,你就不会得到一个用户,然后你就无法从中提取类别
const { categories } = useSelector((state) => state.auth.user ?? {categories: []});
根据你对用户和类别数据的处理方式,你最好这样做:
const user = useSelector((state) => state.auth.user);
if(!user){
return;
}
const categories = user.categories
...