为什么这个redux工具包用户变量总是未定义的?

cgvd09ve  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(149)

我试图在redux工具包切片中添加一个用户到state.users。

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  users: [],
}

export const userManagementSlice = createSlice({
  name: 'userManagement',
  initialState,
  reducers: {
    addUser: (state, action) => {
      const user = action.payload;
      state.users.push(user);
    },
  },
})

// Action creators are generated for each case reducer function
export const { addUser } = userManagementSlice.actions

export default userManagementSlice.reducer

以下是一个组件的关键代码,该组件侦听处于全局状态的用户,并尝试通过分派将用户添加到该数组:

const [firstName, setFirstName] = useState();
const [lastName, setLastName] = useState();
const users = useSelector((state) => state.users)
const dispatch = useDispatch()

const addUser2 = () => {
    const user = {
        firstName,
        lastName
    }
    dispatch(addUser(user));
}

但是,从组件记录到控制台的USERS UPDATED值始终是未定义的:

useEffect(() => {
    console.log('USERS UPDATED: ' + users);

    // reset inputs
    setFirstName('');
    setLastName('');

}, [users]);

下面是configureStore的设置:

import { configureStore } from '@reduxjs/toolkit'
import userManagementReducer from '../features/userManagement/userManagementSlice'

export const store = configureStore({
  reducer: {
    userManagement: userManagementReducer,
  },
})

你知道我做错了什么吗

yhqotfr8

yhqotfr81#

您要在userManagement处挂载片,因此您的选择器必须为

const users = useSelector((state) => state.userManagement.users)

相关问题