Javascript 更改LWC中数组中的对象字段值
我无法在此部分更新数组中的对象字段值Javascript 更改LWC中数组中的对象字段值,javascript,arrays,salesforce,lwc,Javascript,Arrays,Salesforce,Lwc,我无法在此部分更新数组中的对象字段值 this.wiredProducts[0].Price__c = this.selectedRate; 我可以得到这个值,但不能用它做任何事情。它抛出这样的错误: [NoErrorObjectAvailable]脚本错误 所以可能有人知道这个问题。 代码如下 import { LightningElement, wire, track, api } from 'lwc'; import getActiveProducts from '@
this.wiredProducts[0].Price__c = this.selectedRate;
我可以得到这个值,但不能用它做任何事情。它抛出这样的错误:
[NoErrorObjectAvailable]脚本错误
所以可能有人知道这个问题。
代码如下
import { LightningElement, wire, track, api } from 'lwc';
import getActiveProducts from '@salesforce/apex/GetActiveProducts.getSearchedProducts';
export default class IterationInLwc extends LightningElement {
@api searchedName;
@api searchedPrice;
wiredProducts;
rates;
@api selectedRate = 1;
@track searchedProducts;
@track error;
@wire(getActiveProducts)
wiredProduct({ error, data }) {
if (data) {
console.log(data);
this.wiredProducts = data.productList;
this.rates = data.rates;
this.searchedProducts = this.wiredProducts;
console.log(this.prices);
console.log(this.searchedProducts);
} else if (error) {
this.error = error;
}
}
handleSearchByName(event){
this.searchedName = event.target.value;
this.searchedProducts = this.wiredProducts.filter
(product => product.Name.includes(this.searchedName) && product.Price__c >= this.searchedPrice);
}
handleSearchByPrice(event){
this.searchedPrice = parseFloat(event.target.value);
this.searchedProducts = this.wiredProducts.filter
(product => product.Name.includes(this.searchedName) && product.Price__c >= this.searchedPrice);
}
handleMenuSelect(event) {
this.selectedRate = event.detail.value;
this.wiredProducts[0].Price__c = this.selectedRate;
}
}
我找到了解决办法。问题就在这里`
this.wiredProducts = data.productList;
我把这个换成了
this.wiredProducts = JSON.parse(JSON.stringify(data.productList));
一切都好起来了。我猜我们从电线上收到的数据是只读的。所以我们可以用这个技巧解锁它。如果有人知道其他解决方案,请将其张贴在此处,如下所示:
传递给组件的对象是只读的。为了改变数据,一个
组件应该为它想要变异的对象创建一个浅拷贝
因此,您提供的解决方案是正确的想法,但不是正确的实现。要创建记录的浅层克隆,应使用spread运算符或Object.assign() 您也可以尝试这种方式,这样就无需解析和字符串化JSON
this.wiredProducts = {...data.productList};