简体   繁体   中英

Using component key to delete element from array Reactjs

So my code works, but I just wanted clarification whether this is good coding practice or if it will cause problems later on.

As a bit of background this is similar to my previous question How to filter through array of components/elements in reactjs . But this time, instead of filtering an array of dom elements, I'm filtering an array of components. Here's how I did it:

Parent:

delete_this(index)
{   
    let key = index._reactInternalInstance._currentElement.key;
    this.repeats = this.repeats.filter( (item) =>  
    {   
        return item.key !== key;
    }); 
    this.setState({ repeats: this.repeats });  
} 

Child:

delete_this(value)
{   
    this.props.delete_this(value);
}  
render()
{
    <button onClick={this.delete_this.bind(this, this)} ref={ (input) => { this.button = input; } }>delete</button>
}

I tried doing a filter on the object itself but it didn't work so I used the key instead.

As mentioned in your other question that is very similar to this, you should not be relying on internal property like _reactInternalInstance .

They're "private" and the React team can technically deprecate it at any time. I don't know the React teams policy on semver, but I highly doubt changes to an internal api count as a breaking change.

So to answer your question, yes it will possibly cause issues down the line.

You can simply pass in the id to the delete method directly:

<button onClick={() => this.props.delete_this(this.props.id)}>delete</button>

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