如何更改嵌套的Object而不在Redux中进行变更

时间:2016-12-06 08:34:23

标签: javascript object redux

我是redux的新人。我有点担心如何在不改变的情况下更改这些数据。

我的数据结构

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

          {  
            id:dc5c5d7c5s,
            caption:null


            },
             {  
            id:dccccccc5s,
            caption:null


            }





        ],
   }

此功能触发

this.props.updateCaption(ID,标题)

我的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
    }
}

1 个答案:

答案 0 :(得分:5)

如果状态对象具有多个级别,则在没有变异的情况下很难改变状态。在这些场景中,我首先深入复制状态,然后更改新状态并返回新状态。见Cloning object deeply。你可以尝试一次。

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;
   }
}