为什么拼接方法只删除 React 中的第一个数组索引?

Why is splice method removing only first array index in React?

我正在使用 PokeAPI 在 React 中制作一个小应用程序,并且在使用 splice() 方法从数组(团队)中删除元素(宠物小精灵)时遇到问题。无论我选择删除哪个元素,它只会删除数组中的第一个元素。

这是通过 props 向下传递的函数,我正在使用它来删除项目。

removePokemon = (index) => {
  const team = [...this.state.team]
   team.splice(index, 1)
   this.setState({team})
  }

这是实际使用的 Team 组件。

import React, { Component } from 'react';
import Button from 'react-bootstrap/Button'


class Team extends Component {
    render() {
        return (
            <div>
                <h2>{this.props.trainer && <p>{this.props.trainer}'s Team</p>}</h2>
                {this.props.team &&
                <div>
                    {this.props.team.map((pokemon, i) => (
                        <div key={pokemon.id}>
                            <span className='cardHeader'>#{pokemon.id} - {pokemon.name}</span>
                            <img src={pokemon.sprites.front_default} alt={pokemon.name}/>
                            <Button onClick={this.props.removePokemon}>Remove from team</Button>
                        </div>
                    ))}
                </div>
                }

            </div>
        );
    }
}

export default Team;

您没有将参数 index 传递给您的函数 removePokemon:

您需要编辑一行:

<Button onClick={() => this.props.removePokemon(i)}>Remove from team</Button>

因为您没有将 index 作为参数传递给 onClick={this.props.removePokemon}

indexremovePokemon 方法中引用事件对象。所以代码

team.splice(index, 1) 计算结果为 team.splice(eventObject, 1).

这就是 splice 删除数组第一个元素的原因。

您可以更改为onClick={() => this.props.removePokemon(i)}以删除您想要的元素。