如何在 Redux 中更改嵌套对象而不对其进行变异 [英] How to change nested Object without mutating it in Redux

查看:55
本文介绍了如何在 Redux 中更改嵌套对象而不对其进行变异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 redux 的新手.我对如何在不改变数据的情况下更改这些数据感到有些困惑.

I am pretty new guy to redux.I am little bit confused that how to change this data without mutating it.

我的数据结构是这样的

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

          {  
            id:dc5c5d7c5s,
            caption:null


            },
             {  
            id:dccccccc5s,
            caption:null


            }





        ],
   }

这个函数什么时候触发

this.props.updateCaption(id,caption)

this.props.updateCaption(id,caption)

我的 Reducer 应该根据数据结构中的 id 设置数据而不对其进行变异

my Reducer should set data according to the id in the data structure without mutating it

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

这篇关于如何在 Redux 中更改嵌套对象而不对其进行变异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆