简体   繁体   English

Redux操纵状态对象

[英]Redux manipulate state object

My target is to add element of mapped array into redux object. 我的目标是将映射数组的元素添加到redux对象中。 Example: List of Students json 示例:学生名单json

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

In Redux I have: 在Redux我有:

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

My target is data to look like that: 我的目标是看起来像这样的数据:

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

I need add user object as a prop of person object in Object assign. 我需要在Object assign中添加用户对象作为person对象的prop。 How is that possible. 怎么可能。 Which is most correct way to do that? 哪种方法最正确?

You can use map() method on passed list of students to add new property to each object inside and then use spread syntax in object and array to add those new properties. 您可以对传递的学生列表使用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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM