简体   繁体   中英

How to delete a specific element from an component array?

When my code executes to remove an element, the last array element gets deleted, not the specific index I am referring to in the code.

Any assistance in reviewing this would be helpful.

constructor(props) {
    super(props);
    this.state = {
        rows: []
    }
    this.addHandler = this.addHandler.bind(this);
    this.removeHandler = this.removeHandler.bind(this);
}
addHandler(event){
    const rows = this.state.rows.concat(<Component>);
    this.setState({
                    rows
    })
}

removeHandler(id){
    const index = id;
    this.setState({
        row: this.state.row.filter( (x, i) => i !== index) 

    })
}

render () {
    const rows = this.state.rows.map((Element, index) => {
        return <Element key={index} id={index} index={index} func1= 
        {this.addHandler} func2={this.removeHandler} />
    });
    // func2 gets called by child
    return (
            <div className="rows">

                <button onClick={this.addHandler} >+</button>

                {rows}
             </div>
    );
}

Don't use index as a key for mapping out an array. Check out this package, easy to use and get the job done uuid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM