Answer the question
In order to leave comments, you need to log in
Why does the remove function force react to render the element being removed?
Hi all. Help, I'm learning react and even got confused. Here is the code, the question is in the title.
constructor ()
{
super();
this.state = { items: [
{ id: 0, text: 'Lorem ipsum dolor sit amet.' },
{ id: 1, text: 'Lorem ipsum.' },
{ id: 2, text: 'Lorem ipsum.1' }
] }
}
// Функция удаления элемета
removeItem ( index )
{
for ( let item in this.state.items )
{
if ( index === this.state.items[item].id )
{
let newArr = this.state.items.splice( index, 1 );
this.setState( { items: newArr } );
}
}
alert( JSON.stringify(this.state) + " index " + index );
}
render ()
{
return (
this.state.items.map( ( item, index ) =>
<div class="note-container">
<div class="note-hidden-controls">
<button onClick={ () => this.removeItem( index ) } class="nhc-btn">
<i className="fas fa-trash"></i>
</button>
<button class="nhc-btn">
<i className="fas fa-edit"></i>
</button>
</div>
<h2>
{ item.text }
</h2>
</div>
)
);
}
Answer the question
In order to leave comments, you need to log in
We carefully read what the Array.prototype.splice method returns .
removeItem(index) {
const newItems = [...this.state.items];
newItems.splice(index, 1);
this.setState({ items: newItems });
}
removeItem(id) {
this.setState({
items: this.state.items.filter(item => item.id !== id),
});
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question