Redux 操作状态对象

Redux manipulate state object

我的目标是将映射数组的元素添加到 redux 对象中。例子: 学生名单 json

[
    {id: "1", name: "Anie"},
    {id: "2", name: "John"}
]

在 Redux 中我有:

const initialState = {
  students: []
}
const students = (state = initialState, action) => {
  switch (action.type) {
    case 'ALL_STUDENTS':
      return Object.assign({}, state, {
        students: action.students
      })
    }
}

我的目标是让数据看起来像这样:

[
    {someprop: "", student: {id: "1", name: "Anie"}},
    {someprop: "", student: {id: "2", name: "John"}}
]

我需要在对象分配中添加用户对象作为人员对象的道具。这怎么可能。哪种方法最正确?

您可以在传递的学生列表上使用 map() 方法向其中的每个对象添加新的 属性,然后在对象和数组中使用扩展语法添加这些新属性。

const initialState = {
  students: []
}
const students = (state = initialState, action) => {
  switch (action.type) {
    case 'ALL_STUDENTS':
      return {
        ...state,
        students: [...action.payload.map(student => {
          return {someprop: '', student}
        })]
      }
          
    default:
      return state;
  }
}

var newStudents = {
  type: 'ALL_STUDENTS',
  payload: [{id: "1", name: "Anie"},{id: "2", name: "John"}]
}

let state = students(undefined, newStudents);
console.log(state)