简体   繁体   中英

How should I update the Redux state in my React App?

I'm working on a React project, and I have a section with "Saved Games".

The "Saved Games" section maps the "Saved Games" state.

This is what it looks like:

let SavedGamesList = <h1>Loading...</h1>;
if (this.props.savedGamesState.length < 1) {
  SavedGamesList = <StyledNotSavedGames>Such empty</StyledNotSavedGames>;
}

if (this.props.savedGamesState.length >= 1) {
  SavedGamesList = this.props.savedGamesState.map(game => (
    <GameCard
      key={game.game}
      title={game.title}
      hoursViewed={game.hours_viewed}
      saved={true}
    />
  ));
}

When I try to delete a game, it deletes a random one not the one I clicked, or multiple games at once.

This is what the "GameCard" (Where the delete button is) looks like:

deleteGame = () => {
  let gameName = this.props.title;
  this.props.deleteGame(gameName); //This is the Redux dispatch
  console.log(this.props.savedGamesState);
};

And this is how I try to change the state in the Reducer:

  case actionTypes.DELETE_GAME:
    let updatedGames = [
      ...state.savedGames.splice(
        state.savedGames.findIndex(e => e.title === action.payload),
        1
      )
    ];
    return {
      ...state,
      savedGames: updatedGames
    };

Edit: Dispatch to props:

deleteGame: (res) => dispatch({type: actionType.DELETE_GAME, payload: res})

I also noticed that the last game in the list can't be deleted, the state updated but the component doesn't re-render so it's not disappearing.

Something in the reducer probably is wrong, what do you think?

I think your problem is that the return value of splice is the array of removed games, try something like that (note you can also use the filter method):

    case actionTypes.DELETE_GAME:{
        let updatedGames = [
          ...state.savedGames
        ];
        updatedGames.splice(
            updatedGames.findIndex(e => e.title === action.payload),
            1
        )

        return {
          ...state,
          savedGames: updatedGames
        };
}

also I think it is better for you to use the key of the game to remove it and not the title unless the title is unique

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