Javascript 从状态数组中删除项时的奇怪行为
我有一个状态为的数组,其中包含各种组件。当我单击其中一个组件上的“删除”按钮时,它会从数组中删除第一个项。我似乎只有在数组中使用组件时才会遇到这个问题,它可以很好地处理字符串数组 父组件:Javascript 从状态数组中删除项时的奇怪行为,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,我有一个状态为的数组,其中包含各种组件。当我单击其中一个组件上的“删除”按钮时,它会从数组中删除第一个项。我似乎只有在数组中使用组件时才会遇到这个问题,它可以很好地处理字符串数组 父组件: addItem = (block) => { const add = [...this.state.items, block]; this.setState({items: add}) } removeItem = (index) => { const remove = [...th
addItem = (block) => {
const add = [...this.state.items, block];
this.setState({items: add})
}
removeItem = (index) => {
const remove = [...this.state.items];
remove.splice(index, 1);
this.setState({items: remove})
}
render(){
return(
<div className="Board">
<div className="BoardContainer">
{this.state.items.map((item, index) => { return <Item remove= {this.removeItem} key={index} >{item}</Item>})}
</div>
<button onClick={() => this.addItem(<BannerImage />)}>Banner Image</button>
<button onClick={() => this.addItem(<ShortTextCentered />)}>Short Text Centered</button>
</div>
)
}
export class Item extends React.Component {
handleRemove = () => {
this.props.remove(this.props.index)
}
render() {
return (
<div className="item">
{this.props.children}
<button onClick={this.handleRemove} >Remove</button>
</div>
)
}
}
子组件:
addItem = (block) => {
const add = [...this.state.items, block];
this.setState({items: add})
}
removeItem = (index) => {
const remove = [...this.state.items];
remove.splice(index, 1);
this.setState({items: remove})
}
render(){
return(
<div className="Board">
<div className="BoardContainer">
{this.state.items.map((item, index) => { return <Item remove= {this.removeItem} key={index} >{item}</Item>})}
</div>
<button onClick={() => this.addItem(<BannerImage />)}>Banner Image</button>
<button onClick={() => this.addItem(<ShortTextCentered />)}>Short Text Centered</button>
</div>
)
}
export class Item extends React.Component {
handleRemove = () => {
this.props.remove(this.props.index)
}
render() {
return (
<div className="item">
{this.props.children}
<button onClick={this.handleRemove} >Remove</button>
</div>
)
}
}
您在组件内部使用了“this.props.index”,但没有将索引传递给组件 你应该这样做:
{this.state.items.map((item, index) => { return <Item remove={this.removeItem} key={index} index={index} >{item}</Item>})}
Array.prototype.splice会使数组发生变异,因此最好不要将splice与React一起使用 最容易使用Array.prototype.filter创建新阵列 此外,使用唯一id而不是索引可以防止意外结果
let filteredArray = this.state.item.filter(x=> x!== e.target.value)
this.setState({item: filteredArray});