【问题标题】:Using object rest to delete nested object使用 object rest 删除嵌套对象
【发布时间】:2018-02-25 07:12:59
【问题描述】:

我有一个带有一些 redux 状态的 react 应用程序,如下所示:

{
    shape1: {
        constraints: {
            constraint1: {
                key: value
            },
            constraint2: {
                key: value
            }
        }
    }, 
    shape2: {
        constraints: {
            constraint1: {
                key: value
            },
            constraint2: {
                key: value
            }
        }            
    }
}

我调度了一个动作并想要删除其中一个约束对象,即。形状 1 的约束 1。这是我的减速器在此操作中的样子,假设我正在尝试从 shape1 中删除约束 1:

case DELETE_CONSTRAINT:
    shape = action.payload;    // ie. shape1, the parent of the constraint I 
                               // am trying to delete
    let {
        [shape]: {'constraints': 
            {'constraint1': deletedItem}
        }, ...newState  
    } = state;
    return newState;

这会从状态中删除整个 shape1 对象,而不仅仅是单个约束 1 对象。我哪里出错了/这样做的最佳方法是什么?为了与我的其余代码保持一致,我更喜欢使用对象休息。

谢谢。

【问题讨论】:

    标签: reactjs ecmascript-6 redux ecmascript-next


    【解决方案1】:

    在解构中使用 rest 语法来获取对象的切片时,您将在同一“级别”上获取其他所有内容。

    let {
        [shape]: {'constraints': 
            {'constraint1': deletedItem}
        }, ...newState  
    } = state;
    

    在这种情况下,newState 接受除了[shape] 之外的一切。

    由于您的状态有多个嵌套级别,您必须使用解构和休息语法提取新的约束,然后创建一个新的状态。

    const state = {
        shape1: {
            constraints: {
                constraint1: {
                    key: 'value'
                },
                constraint2: {
                    key: 'value'
                }
            }
        }, 
        shape2: {
            constraints: {
                constraint1: {
                    key: 'value'
                },
                constraint2: {
                    key: 'value'
                }
            }            
        }
    };
    
    const shape = 'shape1';
    const constraint = 'constraint1';
      
    // extract constraints
    const {
      [shape]: {
        constraints: {
          [constraint]: remove,
          ...constraints
        }  
      }
    } = state;
    
    // create the next state
    const newState = {
      ...state,
      [shape]: {
        ...state[shape], // if shape contains only constraints, you keep skip this
        constraints
      }
    }
    
    console.log(newState);

    【讨论】:

      【解决方案2】:

      简而言之,不是没有对象 - 不是扩展运算符。

      您可以通过其他方式而不改变您的状态,例如过滤器,例如:

      return state.filter((element, key) => key !== action.payload);
      

      一致性旁注

      作为旁注 - 方法和风格的一致性与实际代码的一致性之间存在巨大差异。如果以不同的方式做更合乎逻辑的话,不要觉得有必要为了保持一致性而硬着头皮做某事。如果它确实破坏了其他开发人员正在开发的应用程序的一致性,请记录它为什么不同。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-25
        相关资源
        最近更新 更多