我试图在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,
},
})
你知道我做错了什么吗
1条答案
按热度按时间yhqotfr81#
您要在
userManagement
处挂载片,因此您的选择器必须为