我正在尝试在我的reducer中更新嵌套数据。使用以下操作,我将在我的reducer中返回一个数组映射。但是我的状态没有改变:
case "SUBMIT_ANSWER":
const { current, results, completed } = action.data;
return state.map(video =>
video.id === action.id
? { ...video, current, results, completed }
: video
);
行动:
{
type: "SUBMIT_ANSWER", data: {…}}
data:
completed: false
current: 1
id: 142
results: {correctAnswers: 1, score: 5}
}
需要更新的数据:
{
videos: [{
bookMarked: false
completed: false
correctScore: 5
current: 0
description: "<p>Lorem ipsum dolor sit amet</p>↵"
iconPath: "require('../assets/images/venepuncture.png')"
id: 142
preview: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut"
questions: (15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
results: {score: 0, correctAnswers: 0}
title: "Venepuncture"
totalScore: 50
youtubeVideo: "cxcxcx"
}
......
]}
假设以下嵌套状态:
{
itemA: 'bla',
name: [
{a: 2, b:3, value:'John', lannguages:['pt','en']}
],
obj:{
obj2:{
nestedArray : [1,2,3]
}
}
}
现在,假设您要更新nestedArray
道具响应UPDATE_ARRAY
动作,并传递一个数字作为action.data
连续值:
switch(action.type){
case 'UPDATE_ARRAY': return{
...state,
obj:{
...state.obj,
obj2:{
...state.obj.obj2,
nestedArray : state.obj.obj.nestedArray.concat(action.data)
}
}
}
}
只需按正确的顺序使用点差运算符,就可以了!