如何在 reducer 的 map 函数中为状态赋值
How to assign value to a state inside a map function of a reducer
试图传递一张卡片的点击类型值,我想得到的是那张卡片的类型。 state.memoryCards 在日志中输出以下内容:
- 0:{名称:"Aircraft",类型:“200”,最大速度:880,图像名称:"a1",...}
- 1:{名称:"Aircraft",类型:“300”,最大速度:880,图像名称:"a2",……}
- 2:{名称:"Aircraft",类型:“200ER”,最大速度:920 imageName:"a8",...}
- 3:{名称:"Aircraft",类型:“300ER”,最大速度:920 imageName:"a9",...}
如您所见,state.currentCardType = card.type 不是一个好习惯,因为状态正在发生变化。因此,我想重构代码,但不确定如何编写,因为它在 map 函数中。
case types.CARD_CHECK: {
return {
...state,
memoryCards: state.memoryCards.map((card, index) => {
console.log(state.memoryCards)
if(index === action.index) {
state.currentCardType = card.type; <---- I am talking about this on
return {
...card,
flipped: !card.flipped
}
}
return card
})
}
}
你可以像这样先导出修改后的memoryCards
,然后再分别导出currentCardType
case types.CARD_CHECK: {
let memoryCards = state.memoryCards.map((card, index) => {
if (index === action.index) {
return {
...card,
flipped: !card.flipped
}
}
return card
});
let currentCardType = state.memoryCards[action.index].type; // since your are checking array index with action.index
return {
...state,
memoryCards,
currentCardType
}
}
试图传递一张卡片的点击类型值,我想得到的是那张卡片的类型。 state.memoryCards 在日志中输出以下内容:
- 0:{名称:"Aircraft",类型:“200”,最大速度:880,图像名称:"a1",...}
- 1:{名称:"Aircraft",类型:“300”,最大速度:880,图像名称:"a2",……}
- 2:{名称:"Aircraft",类型:“200ER”,最大速度:920 imageName:"a8",...}
- 3:{名称:"Aircraft",类型:“300ER”,最大速度:920 imageName:"a9",...}
如您所见,state.currentCardType = card.type 不是一个好习惯,因为状态正在发生变化。因此,我想重构代码,但不确定如何编写,因为它在 map 函数中。
case types.CARD_CHECK: {
return {
...state,
memoryCards: state.memoryCards.map((card, index) => {
console.log(state.memoryCards)
if(index === action.index) {
state.currentCardType = card.type; <---- I am talking about this on
return {
...card,
flipped: !card.flipped
}
}
return card
})
}
}
你可以像这样先导出修改后的memoryCards
,然后再分别导出currentCardType
case types.CARD_CHECK: {
let memoryCards = state.memoryCards.map((card, index) => {
if (index === action.index) {
return {
...card,
flipped: !card.flipped
}
}
return card
});
let currentCardType = state.memoryCards[action.index].type; // since your are checking array index with action.index
return {
...state,
memoryCards,
currentCardType
}
}