gpt4 book ai didi

javascript - 使用 $splice 从状态中删除嵌套元素 - React

转载 作者:太空宇宙 更新时间:2023-11-04 16:15:40 24 4
gpt4 key购买 nike

我正在尝试从 Component 状态中删除一个元素。这就是状态中感兴趣的部分的样子:

this.state({user:{
...
instruments: [
0: {
name:"bass guitar",
experience: "2"
}
1: {
name:"drums",
experience: "1"
}
...
]
}})

当用户单击按钮时,我想从状态中删除该元素。使用以下代码,数组中的第一个元素始终被删除,因为 splice 无法访问内部 name 属性。有什么想法吗?

Instrument.js

remove(){
this.props.removeInstrument(this.props.name);
}

render(){
return(
<article className="instrument">
<Col xs={12} sm={6}>
<div className="container-elements">
<span className="delete-element" onClick={this.remove.bind(this)}>x</span>
<h3>{this.props.name}</h3>
<p>{this.props.experience} years of experience</p>
</div>
</Col>
</article>
);
}

EditProfile.js

    removeInstrument(val) {
console.log('clicked on remove! ', val);
this.setState({
user: update(this.state.user, {instruments: {$splice: [[val,1]]}})
})
}

// this is how I render the instrument
<div className="container-tags">
{this.state.user.instruments.map((instrument, index) => {
return <Instrument key={instrument.name} removeInstrument={this.removeInstrument} name={instrument.name} experience={instrument.experience}/>;
})}
</div>

最佳答案

您可以使用数据的索引来删除它,而不是使用名称

Instrument.js

remove(){
this.props.removeInstrument(this.props.index);
}

render(){
return(
<article className="instrument">
<Col xs={12} sm={6}>
<div className="container-elements">
<span className="delete-element" onClick={this.remove.bind(this)}>x</span>
<h3>{this.props.name}</h3>
<p>{this.props.experience} years of experience</p>
</div>
</Col>
</article>
);
}

EditProfile.js

removeInstrument(val) {
console.log('clicked on remove! ', val);
this.setState({
user: update(this.state.user, {instruments: {$splice: [[val,1]]}})
})
}

// this is how I render the instrument
<div className="container-tags">
{this.state.user.instruments.map((instrument, index) => {
return <Instrument key={instrument.name} removeInstrument={this.removeInstrument} name={instrument.name} experience={instrument.experience} index={index}/>;
})}
</div>

关于javascript - 使用 $splice 从状态中删除嵌套元素 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41097893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com