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

时间:2016-12-12 09:40:15

标签: javascript reactjs state splice

我正在尝试从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>

1 个答案:

答案 0 :(得分:1)

您可以使用index数据删除它,而不是使用name

<强> 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>