2016-12-12 7 views
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> 
+1

a)のインデックスを渡すと、インデックスではなく名前で削除し、b)の名前で要素を削除するには、 'filter'を使用し、すなわち'楽器:この.state.user.instruments.filter(instrument => instrument.name!== val) ' – pawel

答えて

1

あなたはデータのindexを使用して、というよりもname

インストゥルメントを使用していることを削除することができます。 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> 
+0

パーフェクト!それは簡単な修正だった、ありがとう! –

関連する問題