【发布时间】:2020-08-09 20:28:13
【问题描述】:
我正在尝试制作一个价格数组,它的逻辑包含在这个函数中
function getPrices(qty: number, id: string) {
let mappedPrices = inCart.map(item => item.price)
let product = inCart.find(item => item.id === id)
const itemIndex = mappedPrices.indexOf(product.price)
const newPrice = qty * product.price
if (~itemIndex) {
mappedPrices[itemIndex] = newPrice
} else {
mappedPrices
}
console.log(mappedPrices)
}
//inCart types -- [{name: string, image: string, price: number, id: string}]
//Example = [{name: 'shoe', image: 'shoe.png', price: 30, id: 'shoeid'}]
每次我控制台记录它时,都会对一个数字进行更改,但另一个会返回到它的初始值。关于如何解决它的任何线索?
每个 cartItem 组件都会调用 getPrice 函数
useEffect(() => {
getPrices(qty, data.id)
}, [qty])
【问题讨论】:
-
请添加一些数据例如
-
mappedPrice 只包含价格,所以
mappedPrices.indexOf(product.price)是一个非常糟糕的主意,以防有两种价格相同的产品。 -
你完全正确,但我想不出其他解决方案
标签: javascript arrays reactjs typescript