React redux - 更新状态中的嵌套数组

时间:2017-11-23 15:20:29

标签: javascript reactjs react-redux immutability

我在react redux中尝试了一些应用程序,我在更新(推送,删除,更新)状态的嵌套数组时遇到问题。

我有一个像这样的服务对象:

{
    name: 'xzy',
    properties: [
       { id: 1, sName: 'xxx'},
       { id: 2, sName: 'zzz'}, 
    ]
}

无论我在减少器中使用属性集合做了什么(在向集合添加属性的情况下)都会产生问题,即所有属性都与我最近添加的最后一个属性具有相同的值 - >添加的属性对象位于服务属性集合中,但该操作将替换此集合中所有属性中的所有值。 我的减速机:

export function service(state = {}, action) {
        switch (action.type) {
            case 'ADD_NEW_PROPERTY':
                console.log(action.property) // correct new property
                const service = {
                    ...state, properties: [
                        ...state.properties, action.property
                    ]
                }
                console.log(service); // new property is pushed in collection but all properties get same values
                return service

            default:
                return state;
        }
    }

我尝试了一些使用immutability-helper库的解决方案,它会产生同样的问题:

export function service(state = {}, action) {
    case 'ADD_NEW_PROPERTY':

                return update(state, {properties: {$push: [action.property]}})

            default:
                return state;
        }

例如,当我向上面的示例添加新属性{ id: 1, sName: 'NEW'}时,我将获得此状态:

{
    name: 'xzy',
    properties: [
       { id: 1, sName: 'NEW'},
       { id: 1, sName: 'NEW'}, 
       { id: 1, sName: 'NEW'}
    ]
}

有人可以帮忙吗? :)

4 个答案:

答案 0 :(得分:1)

同时复制export function service(state = {}, action) { switch (action.type) { case 'ADD_NEW_PROPERTY': console.log(action.property) // correct new property const service = { ...state, properties: [ ...state.properties, { ...action.property } ] } console.log(service); // new property is pushed in collection but all properties get same values return service default: return state; } }。无论调度此动作是什么,它都可以重用相同的对象。

node-gyp

答案 1 :(得分:1)

我建议您使用不可变数据https://facebook.github.io/immutable-js/docs/#/List

import { fromJS, List } from 'immutable';

const initialState = fromJS({
  propeties: List([{ id: 1, sName: 'xyz' }]
}

function reducer(state = initialState, action) {
  case ADD_NEW_PROPERTY:
    return state
      .update('properties', list => list.push(action.property));
 // ...
}

答案 2 :(得分:0)

您的服务缩减器应该看起来像这样:

// Copy the state, because we're not allowed to overwrite the original argument
const service = { ...state }; 
service.properties.append(action.property)
return service

答案 3 :(得分:0)

您应该在返回之前复制状态。

  export default function(state = {}, action) {
  switch(action.type) {
    case 'GET_DATA_RECEIVE_COMPLETE': {
      const data  = action.firebaseData;
      const newState = Object.assign({}, state, {
        data
      });

      return newState
    }
    default:
      return state;

  }
}