简体   繁体   English

array.splice不起作用,它总是删除最后一个元素

[英]array.splice not working it always delete last element

    add() {
    rendercomponent.push(UiInput);
    childJson.push(this.dynamicJson())
    this.setState({ documents: rendercomponent, Json: childJson });

}
componentDidMount() {
    rendercomponent.push(UiInput);
    this.setState({ documents: rendercomponent })
}
dynamicJson() {
    return {
        "service": this.state.formValues.text,
        "tax": this.state.formValues.tax,
        "amount": this.state.formValues.amount
    }
}
popComponent = (index) => {
    console.log(`in parent-->>${index}`)
    rendercomponent.splice(index, 1);
    childJson.splice(index, 1);
    this.setState({ documents: rendercomponent,Json: childJson,formValues:{} })

};  render() {
    return (
        <div>
    {this.state.documents.map((Element, index) => {
                                    return <Element key={index} index={index} onUpdate={this.onUpdate} popComponent={() => this.popComponent(index)} />
                                })}
          </div>
);
}

array.splice not working correctly it always deletes the last element from the array array.splice无法正常工作,它总是从数组中删除最后一个元素

In my UI there is one button to add component, on that button add() function is called 在我的用户界面中,有一个按钮可以添加组件,该按钮上的add()函数被调用

And also there is delete button, on delete button popComponent() function is called. 还有一个删除按钮,在删除按钮上popComponent()函数。

I want to delete the particular element, it always deletes the last element from the redercomponent array. 我想删除特定元素,它总是从redercomponent数组中删除最后一个元素。

please help me to sort this problem 请帮我解决这个问题

splice would mutate an object rendercomponent , but it won't change the reference of that object. splice将使对象的rendercomponent发生变化,但不会更改该对象的引用。 If the reference does not change, the react won't re-render it, as it won't be different as per the react's diffing algorithm. 如果参考没有改变,则反应将不会重新渲染它,因为根据反应的差异算法,反应不会有所不同。 So you can use slice instead of splice . 因此,您可以使用slice而不是splice Such that the new object's reference should be different for the earlier object. 这样,新对象的引用应与先前的对象不同。

Check that rendercomponent!== rendercomponentModified 检查rendercomponent!== rendercomponentModified

perhaps 也许

 popComponent = (index) => {
    console.log(`in parent-->>${index}`)
    var rendercomponentModified = [
     ...rendercomponent.slice(0,index),
     ...rendercomponent.slice(index+1)
    ];
    var childJsonModified = [
           ...childJson.slice(0,index), 
           ...childJson.slice(index+1)
    ];
     this.setState({ documents: rendercomponentModified,
    Json: childJsonModified,formValues:{} });
   }

in case index is -1, rendercomponent.splice(index, 1); 如果index为-1,则rendercomponent.splice(index, 1); will just remove the last item of the array 只会删除数组的最后一项

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

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