[英]UnhandledThrownError! Cannot destructure property 'categories'of '(0 , react_redux__WEBPACK_IMPORTED_MODULE_2__.useSelector)(...)' as it is undefined
Auth.js授权.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 (store) index.js(商店)
import { configureStore } from "@reduxjs/toolkit";
import authReducer from "./auth.js";
export default configureStore({
reducer: {
auth: authReducer,
},
});
transaction form.js交易表格.js
const { categories } = useSelector((state) => state.auth.user);
** when I logged in there was a error but on reloading the page the error is gone. ** 当我登录时出现错误,但在重新加载页面时错误消失了。 How to fix the error**如何修复错误**
If you are not logged in, you don't get a user, and then you cannot extract categories from it.如果你没有登录,你就得不到用户,然后你就不能从中提取类别。 Several solutions, one is几种解决方案,一种是
const { categories } = useSelector((state) => state.auth.user ?? {categories: []});
Depending on what you do with the user and category data, you might be better off doing something like this:根据您对用户和类别数据的处理方式,您最好这样做:
const user = useSelector((state) => state.auth.user);
if(!user){
return;
}
const categories = user.categories
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.