简体   繁体   English

如何从组件数组中删除特定元素?

[英]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 签出这个软件包,易于使用,并完成uuid的工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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