我正在使用 PokeAPI 在 React 中制作一个小型应用程序,并且在使用 splice() 方法从数组(团队)中删除元素(宠物小 Sprite )时遇到问题。无论我选择删除哪个元素,它只会删除数组中的第一个元素。
这是通过 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>
关于javascript - 为什么拼接方法只删除 React 中的第一个数组索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56345313/