UnhandledThrowError!无法析构“(0,react_redux__WEBPACK_IMPORTED_MODULE_2__.useSelector)(...)”的属性“categories”,因为它未定义

mwg9r5ms  于 2023-01-21  发布在  React
关注(0)|答案(1)|浏览(267)

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);

当我登录时出现错误,但重新加载页面时错误消失。如何修复错误

zengzsys

zengzsys1#

如果你没有登录,你就得不到用户,你就不能从中提取类别。

const { categories } = useSelector((state) => state.auth.user ?? {categories: []});

根据您对用户和类别数据所做的操作,您最好执行以下操作:

const user = useSelector((state) => state.auth.user);
if(!user){
  return;
}
const categories = user.categories
...

相关问题