简体   繁体   English

我应该如何在我的 React 应用程序中更新 Redux state?

[英]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".我正在做一个 React 项目,我有一个“保存的游戏”部分。

The "Saved Games" section maps the "Saved Games" state. “保存的游戏”部分映射了“保存的游戏”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:这就是“GameCard”(删除按钮所在的位置)的样子:

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:这就是我尝试在减速器中更改 state 的方式:

  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.我还注意到列表中的最后一个游戏无法删除,state 已更新,但组件没有重新渲染,因此它没有消失。

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):我认为您的问题是 splice 的返回值是已删除游戏的数组,请尝试类似的操作(注意您也可以使用 filter 方法):

    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我也认为你最好使用游戏的键来删除它而不是标题,除非标题是唯一的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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