简体   繁体   English

使用组件键从数组Reactjs中删除元素

[英]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 . 作为背景知识,这与我之前的问题类似: 如何通过reactjs中的组件/元素数组进行过滤 But this time, instead of filtering an array of dom elements, I'm filtering an array of components. 但是这次,我不是过滤dom元素数组,而是过滤组件数组。 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 . 正如您在另一个与此非常相似的问题中提到的那样,您不应依赖_reactInternalInstance类的内部属性。

They're "private" and the React team can technically deprecate it at any time. 他们是“私有的”,React团队可以在技术上随时弃用它。 I don't know the React teams policy on semver, but I highly doubt changes to an internal api count as a breaking change. 我不知道关于semver的React团队政策,但是我高度怀疑将内部api计数更改为重大更改。

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: 您可以直接将id直接传递给delete方法:

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

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

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