在简单组件中,我有过滤器 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)
最佳答案
您的意思是添加到现有的 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/