1
Component
状態から要素を削除しようとしています。
this.state({user:{
...
instruments: [
0: {
name:"bass guitar",
experience: "2"
}
1: {
name:"drums",
experience: "1"
}
...
]
}})
ユーザーがボタンをクリックすると、私は状態からその要素を削除する:これは国家の興味の部分がどのように見えるかです。次のコードでは、スプライスは内部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>
a)のインデックスを渡すと、インデックスではなく名前で削除し、b)の名前で要素を削除するには、 'filter'を使用し、すなわち'楽器:この.state.user.instruments.filter(instrument => instrument.name!== val) ' – pawel