简体   繁体   中英

React/Redux question about dispatching an action to add an item to an array

I am building a flashcard app and I would like to store the id of seen cards in an array so my GET_RANDOM_CARD action does not select the same card twice.

Inside my componentDidMount method, I dispatch the addSeenCard action like so:

addSeenCard(this.props.randomCard)

Here is my portable action creator function for addSeenCard:

export function addSeenCard(randomCard) {


 return {
    type: 'ADD_SEEN_CARD',
    randomCard: randomCard
  }
}

Here is my reducer function:

 case 'ADD_SEEN_CARD':
  return {
      ...state,
     seenCard: [state.seenCard, action.randomCard.id]
    }

However, the Redux tool instead of showing an array with an id value shows an array with a nested empty array and a value of null. I am learning Redux and I am blocked as to where I am going wrong in my code.

Redux state Raw

You need to deconstruct state.seenCard , like you did with ...state :

 case 'ADD_SEEN_CARD':
  return {
      ...state,
     seenCard: [...state.seenCard, action.randomCard.id]
    }

From the above code of reducer, it came to know that "seenCard" will be an array of ids and you have assigned array as the first element of seenCard going forward.

So use a Spread operator to destructure the array of elements.

case 'ADD_SEEN_CARD':
  return {
    ...state,
    seenCard: [
      ...state.seenCard, 
       action.randomCard.id
     ]
  }

Note the 3 dots added on the 5th line of code.

Also, make sure id is always passed to action creator.

I hope this is helpful!

You can use concat state seenCard array and new value Here is your updated reducer function:

 case 'ADD_SEEN_CARD':
 return {
  ...state,
 seenCard: state.seenCard.concat(action.randomCard.id)
}

Thats what I was missing in my reducer, the spread operator. Thank you very much, all your answers work. Because I am storing the random card in the state I have decided to dispatch the ADD_SEEN_CARD function with an empty payload and do this instead:

  case 'ADD_SEEN_CARD':
  return {
    ...state,
    seenCard: state.seenCard.concat(state.randomCard[0].id)
    //  seenCard: [...state.seenCard, state.randomCard[0].id]
    }

Thank you again for all your answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM