When I delete 1 task, everything is fine, I delete another one, which I delete before that. I click on the tick (handleStatusChange) all three appear, how to solve it

Delete 3 task

Appears the one that deleted

import React, {Component} from "react"; import "./scss/style.scss"; import todosArray from "./todosArray" import Header from "./components/Header"; import Todo from "./components/Todo"; class App extends Component { constructor(props) { super(props); this.state = {items: todosArray}; this.handleStatusChange = this.handleStatusChange.bind(this); this.handleDelete = this.handleDelete.bind(this); } handleStatusChange(id) { let resultList = todosArray.map(todo => { if (todo.id === id) { todo.completed = !todo.completed; } return todo; }); this.setState({items: resultList}); } handleDelete(id) { console.log(id); let resultList = todosArray.filter(todo => todo.id !== id); this.setState({items: resultList}); console.log(resultList) } render() { return ( <main> <Header title={this.props.title} todos={this.state.items}/> <section className="todo-list"> { this.state.items.map(todo => < Todo key={todo.id} id={todo.id} title={todo.title} completed={todo.completed} onStatusChange={this.handleStatusChange} onDelete={this.handleDelete} /> ) } </section> </main> ); } } export default App; const todosArray = [ { id: 1, title: "Изучить JavaScript c Николаем", completed: true }, { id: 2, title: "Изучить React", completed: false }, { id: 3, title: "Написать приложение", completed: false } ]; export default todosArray; [![Удаляю 3 задачу][1]][1] 

Appears to that kotra

    3 answers 3

    The problem is somewhere in this line:

     let resultList = todosArray.filter(... 

    I will explain. Each time you delete a list item, you again and again take your initial (full) array of items ( todosArray ). So, after removing one element, you filter this array and write to the state. But .filer does not change the todosArray array, but returns a new one ( todosArray not changed). Removing the second item, you again take the full array and, of course, the item that you deleted will remain and come back.

    How to do it better? One of the options to write something like this:

     let resultList = todosArray = todosArray.filter(... 

    ... but it is better to do this:

     let resultList = this.state.items.filter(... 

      In the handleDelete and handleStatusChange handlers, you use the todosArray constant, and this.state.items is needed

      For example, here, let resultList = todosArray.filter (todo => todo.id! == id);

      As a result, every time you operate not with the state, but with todosArray, which does not change

        Try splice:

         handleDelete(id) { console.log(id); const resultList = [...this.state.items]; resultList.splice(id,1); this.setState({items:resultList}); console.log(resultList) }