T
T
TCloud2019-04-19 02:14:28
React
TCloud, 2019-04-19 02:14:28

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

This is the result that came out:
5cb90496e9f5e608903681.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-19
@OTCloud

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

It would be more correct to remove an element not by index, but by id:
removeItem(id) {
  this.setState({ 
    items: this.state.items.filter(item => item.id !== id), 
  });
}

To do this, pass the id to the handler:
Also, you don't pass the key property: Lists and keys And this formatting of the code is no good. Read the Airbnb Guidelines: Airbnb JavaScript Style Guide Airbnb React/JSX Style Guide

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question