我的目标是将映射数组的元素添加到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。怎么可能。哪种方法最正确?
答案 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)