创建reducer时如何将状态对象分配给不同的对象

How to assign state object to a different object when creating a reducer

在我的 userSlice.js 文件中,我有以下内容:

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

const initialState = {
    Id: 0,
    FirstName: "-",
    LastName: "-",
    EmailAddress: "-",
    Approved: 0,
    UserInfo: {
      DateOfBirth: "-",
      UserId: 0,
      Id: 0,
      CurrentAddress: "-",
      Gender: "-",
      ContactNumber: "-",
      JoinDate: "-"
    }
}


export const userSlice = createSlice({
  name: "user",
  initialState: initialState,
  reducers: {
    setUser: (state, action) => {
      state = action.payload;
    }
  }
});

export const selectUser = (state) => state;

export const { setUser } = userSlice.actions;

export default userSlice.reducer;

然而,每当我 运行 dispatch(setUser(testUser)) 没有任何东西被分配给状态。这是 testUser 对象:

const testUser = {
  Id: 1,
  FirstName: "Test",
  LastName: "Test",
  EmailAddress: "test.test@test.com",
  Approved: 2,
  UserInfo: {
    DateOfBirth: "-",
    UserId: 0,
    Id: 0,
    CurrentAddress: "-",
    Gender: "-",
    ContactNumber: "-",
    JoinDate: "-"
  }
}

有人可以在这里指导我正确的方向吗?有什么理由说 state = action.payload 行不通而说 state.Id = action.payload.Id 行吗?

由于 redux-toolkit 中切片的内部实现,您似乎不能这样做。它使用 Immer 来跟踪 reducer 中应用的更改:(在此处阅读更多内容 https://redux-toolkit.js.org/usage/immer-reducers#immutable-updates-with-immer)。为避免此问题,只需以这种方式创建您的状态:

const initialState = {
    User: { 
        Id: 0,
        FirstName: "-",
        LastName: "-",
        EmailAddress: "-",
        Approved: 0,
        UserInfo: {
            DateOfBirth: "-",
            UserId: 0,
            Id: 0,
            CurrentAddress: "-",
            Gender: "-",
            ContactNumber: "-",
            JoinDate: "-"
        }
    }
}

和减速器:

setUser: (state, action) => {
  state.User = action.payload;
}