【发布时间】:2020-03-05 19:00:24
【问题描述】:
我正在改变 products 数组,并且我正在改变数组中一个元素的 container 对象,比如说 products[0]。我正在为产品第 0 个元素的容器对象分配一个新对象。代码如下。但不是将容器对象更新为给定的新对象,而是将其设置为数组。
查看产品数组索引 0 处的元素。这是我将 container 对象设置为新对象的地方。但是这里它设置了一个数组到 container 对象。请参阅下面的代码。还可以查看索引 1 处元素的 container 对象。在索引 1 处,它是正确的。
(10) products = [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: container: (2) [{…}, {…}]
id: 15
markup_factor: "1.30"
name: "Sohil Test Product"
private: false
profit_factor: "3.00"
recipe: {id: 1, user: null, ingredients: Array(2), unit: "g", quantity: 4, …}
sales_tax: "12.00"
tags: [{…}]
total_price: 17.47
user: 3
__proto__: Object
1: container: {user: null, id: 22, components: Array(1), currency: "EUR", total_price: 0.15, …}
id: 16
markup_factor: "4.00"
name: "demo product 24"
private: false
profit_factor: "4.00"
recipe: {id: 38, user: 3, ingredients: Array(1), unit: "g", quantity: 0, …}
sales_tax: "0.00"
tags: []
total_price: "9.12"
user: 3
__proto__: Object
2: {id: 21, user: 3, name: "DEMO PRODUCT", tags: Array(1), sales_tax: "2.00", …}
3: {id: 22, user: 3, name: "product 2", tags: Array(0), sales_tax: "4.00", …}
4: {id: 23, user: 3, name: "new product coming", tags: Array(1), sales_tax: "3.00", …}
5: {id: 24, user: 3, name: "new product", tags: Array(1), sales_tax: "0.00", …}
6: {id: 25, user: 3, name: "new product", tags: Array(2), sales_tax: "0.00", …}
7: {id: 26, user: 3, name: "sample test", tags: Array(0), sales_tax: "0.00", …}
8: {id: 27, user: 3, name: "new product demo", tags: Array(0), sales_tax: "0.00", …}
9: {id: 28, user: 3, name: "new product 3", tags: Array(0), sales_tax: "1.00", …}
length: 10
__proto__: Array(0)
变异代码为:
export const updateSelectedProduct = selectedContainer => (dispatch, getState) => {
let { selectedProduct } = getState().product;
let { products } = getState().product;
for (var productList = 0; productList < products.length; productList++) {
if (products[productList].id === selectedProduct.id) {
const containerObj = {
components: selectedContainer,
currency: products[productList].container.currency,
id: products[productList].container.id,
name: null,
user: null
};
products[productList].container = containerObj;
}
}
};
【问题讨论】:
-
containerObj中包含的对象不会神奇地转换为 两个 对象的数组。请添加显示实际问题的minimal reproducible example。
标签: javascript arrays reactjs redux