簡體   English   中英

如何從組件數組中刪除特定元素?

[英]How to delete a specific element from an component array?

當我的代碼執行刪除元素時,最后一個數組元素將被刪除,而不是我在代碼中引用的特定索引。

審查此方面的任何幫助將是有幫助的。

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>
    );
}

不要使用索引作為映射數組的鍵。 簽出這個軟件包,易於使用,並完成uuid的工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM