恐怕这应该是显而易见的,因为我的事务是基于普通的Vanille JS。无论如何,无论出于什么原因,我都无法解决我的问题。有谁能帮我吗?
我在reducer:中的代码快照
> case TOGGLE_PRODUCT:
> const newProducts = [...state.allProducts];
> console.log("All products: ", newProducts);
> console.log("Passed product: ", action.productId);
> console.log("Should have found: ", newProducts[1]);
> const toggledProduct = newProducts.findIndex(
> (el) => el.id === action.productId
> );
> console.log("Found: ", toggledProduct);
控制台输出:
All products: Array [
Product {
"amount": 0,
"department": "Molkereiprodukte",
"id": "id1",
"product": "Milch 3,5%",
"status": false,
},
Product {
"amount": 0,
"department": "Molkereiprodukte",
"id": "id2",
"product": "Yoghurt",
"status": false,
},
Product {
"amount": 0,
"department": "Ceralien",
"id": "id3",
"product": "Müsli",
"status": false,
},
]
Passed product: Object {
"id": "id2",
}
Should have found: Product {
"amount": 0,
"department": "Molkereiprodukte",
"id": "id2",
"product": "Yoghurt",
"status": false,
}
Found: -1
为什么find((方法不返回结果???
提前Thx!
您的action.productId
是object
而不是string
const toggledProduct = newProducts.findIndex( (el) => el.id === action.productId.id /** <--here */ );
findIndex
用于查找需要Array.find
才能获得元素数据的元素的期望索引。获得-1
的原因是action.productId是一个对象。您需要比较action.productId.id
const toggledProduct = newProducts.find(el => el.id === action.productId.id );