更新Redux存储以从阵列中删除某些内容不会重新呈现

时间:2017-08-30 22:14:21

标签: reactjs redux react-redux

我正在制作批量添加系统。在系统中,我有一个redux存储属性名称addPlayerList。在这里,我将放置我将批量添加的所有玩家。现在将玩家添加到添加播放器列表不是问题,状态反映了更改并且它正确呈现了材质UI芯片。但是当我通过Chips删除按钮删除它们时,状态会反映在我的redux商店中,但它不会重新呈现页面。所以玩家不再存在于我的商店中,但他仍然出现在页面上。

如果我执行另一次搜索,实质上导致其他东西重新渲染,它将正确修复列表。对此问题的任何帮助将不胜感激。

class AddPlayer extends Component {

  onClick = () => {
    let {addPlayerToList} = this.props;
    addPlayerToList();
  }

  handleRequestDelete(index) {
    //figure out who the sender of it is
    let {removePlayerFromList} = this.props;
    removePlayerFromList(index);
  }

  render() {
    let {addPlayerToList, addPlayerList} = this.props
    let renderPlayersToAdd = () => {
      if (addPlayerList.length === 0) {
        return (
          <p>No Players to add</p>
        )
      }

       return addPlayerList.map((Player, index) => {
        return (
        <Chip 
          key={index} 
          onRequestDelete={this.handleRequestDelete.bind(this, index)}>
          <Avatar src={getImageURL(Player.id)} />
          {Player.name}
        </Chip>
        );
      }) 
    }

    return (
      <div>
         <TypeAhead />
         <RaisedButton onClick={addPlayerToList} label="Add Player" /> 
         {renderPlayersToAdd()}
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    selectedSuggestion: state.selectedSuggestion,
    addPlayerList: state.addPlayerList
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    addPlayerToList(Player) {
      dispatch(actions.addPlayerToList(Player));
    },
    removePlayerFromList(index) {
      dispatch(actions.removePlayerFromList(index));
    }
  }
}

const mergeProps = (stateProps, dispatchProps, ownProps) => {
  return {
    addPlayerToList: () => dispatchProps.addPlayerToList(stateProps.selectedSuggestion),
    addPlayerList: stateProps.addPlayerList,
    removePlayerFromList: (index) => dispatchProps.removePlayerFromList(index)
  }
}

const AddPlayerWithMutation = graphql(AddPlayerMutation)(AddPlayer);
const AddPlayerWithMutationAndState = connect(mapStateToProps, mapDispatchToProps, mergeProps)(AddPlayerWithMutation);
export default AddPlayerWithMutationAndState;

1 个答案:

答案 0 :(得分:3)

removePlayerFromListmake sure you're not mutating the original array的reducer代码中。因此,请勿使用splice(其中包含&#34; p&#34;)。而是做这样的事情

function removeIndex(array, index) {
  return [
    ...array.slice(0,index),
    ...array.slice(index +1)
  ];
};

这将创建一个新数组,而不是指定索引处的值。这应该会导致重新渲染。

我无法承诺这就是错误的所在,但这是我最好的选择。