开发者问题收集

未捕获的类型错误:无法读取未定义的属性(读取“用户”)

2022-06-20
2867
import { createSlice } from '@reduxjs/toolkit';

export const userSlice = createSlice({
  name: 'user',
  initialState: {
    user: null,
  },
  // The `reducers` field lets us define reducers and generate associated actions
  reducers: {
    login: (state, action) => {
      state.user = action.payload;
    },
    logout: (state) => {
      state.user = null;
    },
  },
  
  });
  
export const { login, logout } = userSlice.actions;

export const selectUser = (state) => state.user.user;



export default userSlice.reducer;

Error: userSlice.js:22 Uncaught TypeError: Cannot read properties of undefined (reading 'user') at selectUser (userSlice.js:22:1)

3个回答

您需要使用 configureStore 并使用 useSelector 来获取用户

步骤 1 :

您可以创建名为 store 或任何您想要的名称的新文件

import { configureStore } from "@reduxjs/toolkit";
import User from "./slices/userSlice";

const store = configureStore({
 reducer: {
  User: User,
 },
});

export default store;

步骤 2 :

您需要在 index.js 中添加提供程序,如下所示:

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store/index";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
 <Provider store={store}>
  <App />
 </Provider>
);

步骤 3 :

使用 useSelector 从任何地方获取用户,如下所示:

const user = useSelector((state) => state.User.user); 
console.log(user);
hazem brayek
2022-06-20
export const selectUser = (state) => state.user === null ? '' : state.user.user;
// or
export const selectUser = (state) => state.user === null ? {} : state.user.user;
grekier
2022-06-20

尝试在 createSlice 函数之外声明初始状态

import { createSlice } from '@reduxjs/toolkit';

const initialState = { user: null }

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    login: (state, action) => {
      state.user = action.payload;
    },
    logout: (state) => {
      state.user = null;
    },
  },
  
  });
  
export const { login, logout } = userSlice.actions;

export const selectUser = (state) => state.user.user;

export default userSlice.reducer;

或者简单地将一个对象放在 initialState 的位置

类似

import { createSlice } from '@reduxjs/toolkit';

const initialState = { user: null }

export const userSlice = createSlice({
  name: 'user',
  //you put your initialState object here
  {user : null},
  reducers: {
    login: (state, action) => {
      state.user = action.payload;
    },
    logout: (state) => {
      state.user = null;
    },
  },
  
  });
  
export const { login, logout } = userSlice.actions;

export const selectUser = (state) => state.user.user;

export default userSlice.reducer;
sulaimon-olaniran
2022-06-20