Javascript 反应更新数据库的更新对象值(数量)
因此,我有一个带有产品编号(details.quantityProduct)和客户请求数量(quantity)的项目 在计算其数量(qtyDbUpdate)后,我想更新(details.quantityProduct),但我的函数(changeQty)不更新此内容,而是向newItems添加一个对象(details) 我不明白。请帮帮我谢谢Javascript 反应更新数据库的更新对象值(数量),javascript,reactjs,jsx,Javascript,Reactjs,Jsx,因此,我有一个带有产品编号(details.quantityProduct)和客户请求数量(quantity)的项目 在计算其数量(qtyDbUpdate)后,我想更新(details.quantityProduct),但我的函数(changeQty)不更新此内容,而是向newItems添加一个对象(details) 我不明白。请帮帮我谢谢 const items = [{ 0: {id: "h72boj6td7o", quantity: 6, details: {… d
const items = [{
0: {id: "h72boj6td7o", quantity: 6, details: {… details.quantityProduct}}
1: {id: "wx9pai7o04", quantity: 1, details: {…}}
length: 2
}]
const qtyItems = (items.map(e => e))
const qtyCart = (qtyItems.map (f => (f.quantity) ))
const qtyDbUpdate = (qtyItems.map(f => (f.details.quantityProduct - qtyCart) ))
const [newItems, setNewItems] = useState(items)
const changeQty = () => {
setNewItems(newItems => ({
...newItems, details: {
quantityProduct: qtyDbUpdate,
}
}))
}
console.log('newItems', newItems)
newItems return :
0: {id: "h72boj6td7o", quantity: 6, details: {…}}
1: {id: "wx9pai7o04", quantity: 1, details: {…}}
details:quantityProduct: (2) [NaN, NaN]
有两件事出了问题
const qtyDbUpdate = (qtyItems.map(f => (f.details.quantityProduct - qtyCart) ))
这里您尝试从数组中减去一个数组,此操作的结果为NaN
[3,4] - [1,2]===NaN
这也有一个问题
setNewItems(newItems => ({
...newItems, details: {
quantityProduct: qtyDbUpdate,
}
}))
newItems是一个数组,但是您创建了一个对象,如果您像这样破坏一个数组,您将在结果中得到一个对象,例如
const arr = ['a','b','c']
{...arr} === {0: "a", 1: "b", 2: "c"} // this is what you get in a result
试试看
const changeQty = () => {
setNewItems(items.map(item=>{
const newProductQuantity=item.details.quantityProduct-item.quantity;
return {
...item,
details:{
quantityProduct:newProductQuantity,
}
}
}))
}
有两件事出了问题
const qtyDbUpdate = (qtyItems.map(f => (f.details.quantityProduct - qtyCart) ))
这里您尝试从数组中减去一个数组,此操作的结果为NaN
[3,4] - [1,2]===NaN
这也有一个问题
setNewItems(newItems => ({
...newItems, details: {
quantityProduct: qtyDbUpdate,
}
}))
newItems是一个数组,但是您创建了一个对象,如果您像这样破坏一个数组,您将在结果中得到一个对象,例如
const arr = ['a','b','c']
{...arr} === {0: "a", 1: "b", 2: "c"} // this is what you get in a result
试试看
const changeQty = () => {
setNewItems(items.map(item=>{
const newProductQuantity=item.details.quantityProduct-item.quantity;
return {
...item,
details:{
quantityProduct:newProductQuantity,
}
}
}))
}
感谢您的快速响应和经验教训;)我只是做了一个小小的修改,将值直接添加到
…项中。详细信息,quantityProduct:newProductQuantity
感谢您的快速响应和经验教训;)我只是做了一个小的修改,直接将值…item.details,quantityProduct:newProductQuantity