I've got the following handleChange function in my App component that is supposed to toggle todo items as completed or not completed. As a side note, I intend to update the code to use React Hooks in the future.
import React from "react"
import TodoItem from "./TodoItem"
import todosData from "./todosData"
import './styles.css'
class App extends React.Component {
constructor() {
super()
this.state = {
todos: todosData
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(id) {
this.setState(prevState => {
const updatedTodos = prevState.todos.map(todo => {
if (todo.id === id) {
todo.completed = !todo.completed;
}
return todo
})
return {
todos: updatedTodos
}
})
}
render() {
const todoItems = this.state.todos.map(item => <TodoItem key={item.id} item={item} handleChange={this.handleChange}/>)
return (
<div className="todo-list">
{todoItems}
</div>
)
}
}
The following line as it currently is doesn't update the completed status of the todo.
if (todo.id === id) {
todo.completed = !todo.completed;
}
However if I change it to something like the following, then it updates!?
if (todo.id === id) {
todo.completed = false;
}
However, I want it to toggle the completed status whether it's true or false and I can't see why the example I've used won't work as googling the problem seems to suggest it should.
Does anybody know why my code doesn't work currently? Any help is appreciated.
Aucun commentaire:
Enregistrer un commentaire