使用多个值更新 redux 切片

Updating redux slice with multiple values

我在 React 项目中使用 redux slice 来存储有关当前用户的信息。但是,加载页面时出现以下错误:

TypeError: Cannot read properties of undefined (reading 'name')

Dashboard.js:

export function Dashboard() {
const currentUser = useSelector(state => state.currentUser);
const dispatch = useDispatch();

return (
   <div>
      <p>{currentUser.name}</p>
      <p>{currentUser.description}</p>
   </div>
   <Button onClick={() => dispatch(setCurrentUser(name, description))}>Set user</Button>
);
}

currentUserSlice.js:

import { createSlice } from '@reduxjs/toolkit'

export const currentUser = createSlice({
  name: 'currentUser',
  initialState: {
    name: "",
    description: ""
  },
  reducers: {
    setCurrentUser: (state, action) => {
        return state =  {
            name: action.payload.name,
            description: action.payload.description
        }
    }
  }
})

// each case under reducers becomes an action
export const { setCurrentUser } = currentUserSlice.actions

export default currentUserSlice.reducer

store.js:

import { configureStore } from '@reduxjs/toolkit'

import currentUserReducer from './currentUserSlice'

export default configureStore({
  reducer: {
    currentUser: currentUserReducer,
  }
})

更新 我没有正确地将减速器导入 store.js。但是,既然我已经导入了数据,调度不会更新数据

您在有效载荷中发送了两个值,而不是一个对象。请更新您的调度函数以改为发送对象:

export function Dashboard() {
const currentUser = useSelector(state => state.currentUser);
const dispatch = useDispatch();

return (
   <div>
      <p>{currentUser.name}</p>
      <p>{currentUser.description}</p>
   </div>
   <Button onClick={() => dispatch(setCurrentUser({name, description}))}>Set user</Button>
);
}