简体   繁体   English

如何在Redux中更改嵌套对象而不对其进行更改

[英]How to change nested Object without mutating it in Redux

I am pretty new guy to redux.I am little bit confused that how to change this data without mutating it. 我是redux的新手,我有点困惑如何更改数据而不更改数据。

my data structure like this 我的数据结构是这样的

    {
      postOwnwerName:"",
        postTags:[],
        photos:[

          {  
            id:dc5c5d7c5s,
            caption:null


            },
             {  
            id:dccccccc5s,
            caption:null


            }





        ],
   }

Whent this function fires 该函数何时触发

this.props.updateCaption(id,caption) this.props.updateCaption(id,caption)

my Reducer should set data according to the id in the data structure without mutating it 我的Reducer应该根据数据结构中的ID设置数据,而不会对其进行更改

import * as types from '../Actions/actionTypes';

const initialState = {
    postOwnwerName:"",
    postTags:[],
    photos:[],
};

export default function uploadReducer(state=initialState,action) {
    switch (action.type){
        case types.SETPHOTOSTATE:
            return Object.assign({},state,{ photos:state.photos.concat(action.payload) });
        case types.SETCAPTIONTEXT:

     //this method is not working
            return (
                Object.assign({},state,state.photos.map((data) => {
                    if(data.id == action.payload.id){
                        return Object.assign({},data,{caption:action.payload.caption})
                    }else{
                        return data
                    }
                }))
            )
        default:
            return state
    }
}

if the state object has many level it will be difficult to change state without mutating. 如果状态对象具有许多级别,则不进行更改就很难更改状态。 In those scenario I first copy the state deeply and then make changes to the new state and return new state. 在那种情况下,我首先复制状态,然后更改为新状态并返回新状态。 See here Cloning object deeply . 请参见此处深入克隆对象 You can try this once. 您可以尝试一次。

export default function uploadReducer(state=initialState,action) {
  let newState = JSON.parse(JSON.stringify(state));
  switch (action.type){
    case types.SETPHOTOSTATE:
       newState.photos.push(action.payload);
       return newState;
    case types.SETCAPTIONTEXT:
       newState.photos.map((data) => {
         if(data.id == action.payload.id){
           data.caption = action.payload.caption;
         }
       });
       return newState;
   default:
     return newState;
   }
}

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

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