如何在 reducer 的 map 函数中为状态赋值

How to assign value to a state inside a map function of a reducer

试图传递一张卡片的点击类型值,我想得到的是那张卡片的类型。 state.memoryCards 在日志中输出以下内容:

如您所见,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
    }
}