在简单的组件中,我得到了滤镜道具。我想覆盖存储在变量中的对象属性动态计算属性。 我想要更改应用程序的状态。
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)
答案 0 :(得分:1)
您是要添加到现有的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
的值,而无需在其中添加现有值