javascript - 对象扩展运算符语法无法与 JavaScript 中的计算属性一起正常工作

标签 javascript reactjs object

在简单组件中,我有过滤器 Prop 。我想覆盖存储在变量中的对象属性动态计算属性。 我想要改变应用程序的状态。

var props = {};

// data inside props.filter
    props.filter = {
        "employeeAttributes": [
            {
                "id": 1,
                "attributeName": "FIRST_NAME",
                "attributeType": "TEXT",
                "displayName": "First Name",
                "active": false,
                "attributeValue": ""
            },
        ],
        "companyAttributes": [
            {
                "id": 1,
                "attributeName": "EMPLOYEE_TYPE",
                "attributeType": "SELECT",
                "displayName": "Employee Type",
                "active": false,
                "attributeValue": ""
            },
        ]
    }

    // computed attribute
    let attr = 'companyAttributes';

    // new updatedCompanyAttribute
    const updatedCompanyAttribute = [{
            "id": 2,
            "attributeName": "OFFICE_LOCATION",
            "attributeType": "SELECT",
            "displayName": "Office Location",
            "active": false,
            "attributeValue": ""
        },
    ];

    // nextState
    const nextState = {...props.filter, [attr]: updatedCompanyAttribute };
    console.log(nextState)

最佳答案

Edit vq03pjk0y3

您的意思是添加到现有的 companyAttributes 属性吗?

const updatedCompanyAttribute = {
        "id": 2,
        "attributeName": "OFFICE_LOCATION",
        "attributeType": "SELECT",
        "displayName": "Office Location",
        "active": false,
        "attributeValue": ""
    }

const nextState = {
   ...props.filter, 
   [attr]: [ ...props.filter[attr], updatedCompanyAttribute ] 
};

...props.filter[attr] 将传播 companyAttributes 的所有值以用其预填充新数组,然后 updatedCompanyAttribute 将新值添加到它。

如果你写:

const nextState = {
   ...props.filter, 
   [attr]: updatedCompanyAttribute
};

您要将 companyAttributes 属性的内容替换为 updatedCompanyAttribute 的值,而不添加已有的值

关于javascript - 对象扩展运算符语法无法与 JavaScript 中的计算属性一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51557145/

相关文章:

Javascript toFixed 不舍入

javascript - 未捕获的语法错误 : Unexpected token < reactjs react-pdf

javascript - React + Firebase undefined 使用点击事件

javascript - Ember.js:迭代模型中对象的正确方法?

javascript - 根据循环中的计数器创建具有唯一名称的 JavaScript 对象

Java 使用compareTo比较两个对象

javascript - 在循环/条件语句中未获得预期返回

javascript - jQuery 当使用 iframe 时,我应该尝试合并 jQuery 的内部和外部实例吗?

javascript - 使用 jquery fadeIn 时鼠标跟随问题

javascript - 读取加载页面时返回的脚本的属性