Как присвоить значение состоянию внутри функции карты редуктора - PullRequest
0 голосов
/ 04 июля 2019

Пытался передать значение типа карты, по которому щелкнули мышью, и я хочу получить тип этой карты. state.memoryCards выводит в журнал следующее:

  • 0: {name: "Aircraft", тип: "200", maxSpeed: 880, imageName: "a1",…}
  • 1: {name: "Aircraft", тип: "300", maxSpeed: 880, imageName: "a2",…}
  • 2: {name: "Aircraft", тип: "200ER", maxSpeed: 920 imageName: "a8",…}
  • 3: {name: "Aircraft", тип: "300ER", maxSpeed: 920 imageName: "a9",…}

Как вы можете заметить, state.currentCardType = card.type не является хорошей привычкой, поскольку состояние изменяется. Поэтому я хочу реорганизовать код, но не уверен, как его написать, потому что он находится внутри функции карты.

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
                })
            }
        }

1 Ответ

0 голосов
/ 04 июля 2019

Вы можете сначала получить модифицированный 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
    }
}
...