简体   繁体   English

如何使用 filter() (reactjs) 删除一个项目

[英]how to delete an item using filter() (reactjs)

I would like to delete an item from an item list using filter() .我想使用filter()从项目列表中删除一个项目。 The function to delete the item is in a parent component that I then call in a child component.删除项目的函数在一个父组件中,然后我在子组件中调用它。

here is the function of the parents component:这是父组件的功能:

deletePlayer = (id) => {
    const teamPlayers = this.state.teamPlayers
    teamPlayers.filter(i => i.idTeam !== id)

    console.log('my players: ', teamPlayers);  
}

I pass this function in props:我在 props 中传递了这个函数:

  <//other props...
   strNationality={player.strNationality}
   deletePlayer={(id) => this.deletePlayer(id)}
 /> 
))

I get it from my child:我从我的孩子那里得到:

 deletItem  = (e, id) => {
     console.log('mes propos player: ', this.props.idPlayer);
     this.props.deletePlayer(id)
 }

and this is how I trigger the event:这就是我触发事件的方式:

  <Button 
    onClick={ () => this.deletItem(this.props.idPlayer) } 
    className='button' 
    color='black' 
    type='submit'>

I get the right id but filter() never filters and it finds all my objects.我得到了正确的 id,但filter()从不过滤,它会找到我所有的对象。 It's like he's ignoring the !== id就像他忽略了!== id

How can I do that?我怎样才能做到这一点?

This line is a problem:这一行是一个问题:

teamPlayers.filter(i => i.idTeam !== id)

filter returns a new array once the iterations are complete, it doesn't do the filtering in place.迭代完成后, filter返回一个数组,它不会就地进行过滤。 You need to assign that filtered array to a new variable.您需要将该过滤后的数组分配给一个新变量。 Since filter doesn't mutate the original state array you can just run the process on that to get the new filtered array which you can then log to the console.由于filter器不会改变原始状态数组,因此您可以在其上运行该过程以获取新的过滤数组,然后您可以将其登录到控制台。

const teamPlayers = this.state.teamPlayers.filter(i => i.idTeam !== id));
console.log('my players: ', teamPlayers);

The above answer is correct but within the react context you can do this:上面的答案是正确的,但在反应上下文中你可以这样做:

  deletePlayer = id => {
    this.setState({
      teamPlayers: this.state.teamPlayers.filter(
        player => player.idTeam !== id,
      ),
    });
  };

The issue is that you are not updating the state using setState...问题是您没有使用 setState 更新状态...

You are not updating the state of the teamPlayers , if you are using a functional component and useState , then I would recommend this.您没有更新 teamPlayers 的状态,如果您使用的是功能组件和 useState ,那么我会推荐这个。

deletePlayer = (id) => {
    
    setTeamPlayers(prevTeamPlayers =>prevTeamPlayers.filter(teamPlayer => teamPlayer.idTeam !== id))

  
}

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

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