Reactjs 中的递减函数不起作用
Decrement function in Reactjs doesn't work
我在 17.02 版本中使用 ReactJs 和 React-dom。
我遇到了 中描述的相同问题:使用按钮递增和递减的值。我使用了建议的解决方案,更改了我以前的代码。
来自这个:
handleDecrement = card => {
let cards = [...this.state.cards];
let id = cards.indexOf(card);
cards[id] = {...card };
cards[id].quantità --;
this.setState({ cards });
}
给这个:
handleDecrement = card => {
let cards = [...this.state.cards];
let id = cards.indexOf(card);
cards[id] = {...card };
cards[id].quantità = card[id].quantità > 0 ? (card[id].quantità - 1) : 0;
this.setState({ cards });
}
但我在控制台中看到这个错误 TypeError: 无法读取未定义的属性(读取 'quantità')
我知道意思,但我不明白为什么如果“quantità”(数量)是一个设置为零的道具,我会看到这个错误:
state = {
cards: [
{id:0, nome: 'California', prezzo: 1.99, immagine: california, quantità:0},
{id:1, nome: 'Dragon', prezzo: 3.49, immagine: dragon, quantità:0},
{id:2, nome: 'Dynamite', prezzo: 2.49, immagine: dynamite, quantità:0},
{id:3, nome:'Philadelphia', prezzo:0.99, immagine: philadelphia, quantità:0},
{id:4, nome:'Rainbow', prezzo:2.99, immagine: rainbow, quantità:0},
{id:5, nome:'Shrimp', prezzo:1.49, immagine: shrimp, quantità:0}
]
}
您没有在 handleDecrement
中显示对 card
的引用来自何处,但在某处引用已更改,因此它在 indexOf 中不起作用。相反,创建一个新列表并避免使用突变。
handleDecrement = card => {
const cards = this.state.cards.map(c => c.id === card.id
? {...c, quantità: Math.max(0, c.quantità - 1)}
: c);
this.setState({ cards });
}
我在 17.02 版本中使用 ReactJs 和 React-dom。
我遇到了
来自这个:
handleDecrement = card => {
let cards = [...this.state.cards];
let id = cards.indexOf(card);
cards[id] = {...card };
cards[id].quantità --;
this.setState({ cards });
}
给这个:
handleDecrement = card => {
let cards = [...this.state.cards];
let id = cards.indexOf(card);
cards[id] = {...card };
cards[id].quantità = card[id].quantità > 0 ? (card[id].quantità - 1) : 0;
this.setState({ cards });
}
但我在控制台中看到这个错误 TypeError: 无法读取未定义的属性(读取 'quantità') 我知道意思,但我不明白为什么如果“quantità”(数量)是一个设置为零的道具,我会看到这个错误:
state = {
cards: [
{id:0, nome: 'California', prezzo: 1.99, immagine: california, quantità:0},
{id:1, nome: 'Dragon', prezzo: 3.49, immagine: dragon, quantità:0},
{id:2, nome: 'Dynamite', prezzo: 2.49, immagine: dynamite, quantità:0},
{id:3, nome:'Philadelphia', prezzo:0.99, immagine: philadelphia, quantità:0},
{id:4, nome:'Rainbow', prezzo:2.99, immagine: rainbow, quantità:0},
{id:5, nome:'Shrimp', prezzo:1.49, immagine: shrimp, quantità:0}
]
}
您没有在 handleDecrement
中显示对 card
的引用来自何处,但在某处引用已更改,因此它在 indexOf 中不起作用。相反,创建一个新列表并避免使用突变。
handleDecrement = card => {
const cards = this.state.cards.map(c => c.id === card.id
? {...c, quantità: Math.max(0, c.quantità - 1)}
: c);
this.setState({ cards });
}