Redux操纵状态对象

时间:2017-11-18 14:58:39

标签: javascript reactjs redux react-redux state-management

我的目标是将映射数组的元素添加到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"}}
]

我需要在Object assign中添加用户对象作为person对象的prop。怎么可能。哪种方法最正确?

1 个答案:

答案 0 :(得分:3)

您可以在传递的学生列表中使用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)