在为每个之后修改对象键值对
modify object key value pair after for each
我正在尝试计算一副牌中相同卡片的数量。每次我添加一张卡片时,我想检查我的卡片数组中是否存在同一张卡片。如果该卡已经存在,我想将前一张卡的数量增加 1
我的主要问题是,当我尝试渲染牌组列表时,我根本看不到牌数。我不确定这是我的功能还是我的映射?
state={
cardCount: 0,
currentDeck: [
{
name: 'card1',
count: 0
},
{
name: 'card2',
count: 0
},
{
name: 'card3',
count: 0
}
],
}
//function to check for duplicate cards
// if the card is already in the deck we add +1 to the count of that card
addToDeck = (selection) =>{
let card = {
name: selection,
count: (count)=>{ for(var x in this.state.currentDeck){
if(x.name === selection){
count = x.count+=1
}
else{
count = 0
}
}
}
}
this.setState({currentDeck:[...this.state.currentDeck, card]})
}
//div where I render the decklist
<div className="currentD">
<h4>Deck List</h4>
<ul>
{currentDeck.map((card, index, num) => (
<li className = 'cardinDeckList' key={index}>
<strong>{card.name}</strong><span key={num}>x{card.count}</span>
</li>
))}
</ul>
</div>
您更新状态的方式无效。您的状态将具有名称作为选择的对象并作为函数计数,反应不会在您的嵌套对象中调用函数。
你可以使用map方法来更新计数,如果没有更新你可以在数组中添加新值。
addToDeck = (selection) =>{
let isUpdated = false;
const updatedDeck = this.state.currentDeck.map(c => {
if (c.name === selection) {
isUpdated = true;
return {...c, count: c.count + 1 };
}
return c;
});
if(!isUpdated) {
updatedDeck.push({ name: selection, count: 0 });
}
this.setState({currentDeck: updatedDeck })
}
我正在尝试计算一副牌中相同卡片的数量。每次我添加一张卡片时,我想检查我的卡片数组中是否存在同一张卡片。如果该卡已经存在,我想将前一张卡的数量增加 1
我的主要问题是,当我尝试渲染牌组列表时,我根本看不到牌数。我不确定这是我的功能还是我的映射?
state={
cardCount: 0,
currentDeck: [
{
name: 'card1',
count: 0
},
{
name: 'card2',
count: 0
},
{
name: 'card3',
count: 0
}
],
}
//function to check for duplicate cards
// if the card is already in the deck we add +1 to the count of that card
addToDeck = (selection) =>{
let card = {
name: selection,
count: (count)=>{ for(var x in this.state.currentDeck){
if(x.name === selection){
count = x.count+=1
}
else{
count = 0
}
}
}
}
this.setState({currentDeck:[...this.state.currentDeck, card]})
}
//div where I render the decklist
<div className="currentD">
<h4>Deck List</h4>
<ul>
{currentDeck.map((card, index, num) => (
<li className = 'cardinDeckList' key={index}>
<strong>{card.name}</strong><span key={num}>x{card.count}</span>
</li>
))}
</ul>
</div>
您更新状态的方式无效。您的状态将具有名称作为选择的对象并作为函数计数,反应不会在您的嵌套对象中调用函数。
你可以使用map方法来更新计数,如果没有更新你可以在数组中添加新值。
addToDeck = (selection) =>{
let isUpdated = false;
const updatedDeck = this.state.currentDeck.map(c => {
if (c.name === selection) {
isUpdated = true;
return {...c, count: c.count + 1 };
}
return c;
});
if(!isUpdated) {
updatedDeck.push({ name: selection, count: 0 });
}
this.setState({currentDeck: updatedDeck })
}