温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Update nested state in reducer

javascript - 在减速器中更新嵌套状态

发布于 2020-03-27 10:43:40

我正在尝试在我的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"
}
......
]}

查看更多

查看更多

提问者
Bomber
被浏览
117
Dupocas 2019-07-04 03:59

假设以下嵌套状态:

{
    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)
            }
        }
    }
}

只需按正确的顺序使用点差运算符,就可以了!

发布
问题

分享
好友

手机
浏览

扫码手机浏览