[英]React todo list - Checkbox is not changing
I started to learn React and I'm following a tutorial.我开始学习 React,并且正在学习教程。 I'm trying to change the checkboxes when it's clicked.我正在尝试在单击复选框时更改它。 I checked if handleChange function before writing the setState code and it's working.在编写 setState 代码之前,我检查了 handleChange function 是否正常工作。 I did everything as in the tutorial but when I click to checkboxes, they are not changing.我按照教程中的方式完成了所有操作,但是当我单击复选框时,它们并没有改变。 Looks like I'm missing something.看起来我错过了什么。 Here is the code:这是代码:
App.js:应用程序.js:
import React, { Component } from "react";
import TodoItem from "./TodoItem";
import todosData from "./todosData";
class App extends 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>
)
}
}
export default App;
TodoItem.js: TodoItem.js:
import React from "react";
import "./index.css";
function TodoItem(props) {
return (
<div className="todo-item">
<input
type="checkbox"
checked={props.item.completed}
onChange={() => props.handleChange(props.item.id)}
/>
<p>{props.item.text}</p>
</div>
);
}
export default TodoItem;
todosData.js: todosData.js:
const todosData = [
{
id: 1,
text: "Take out the trash",
completed: true
},
{
id: 2,
text: "Grocery Shopping",
completed: false
},
{
id: 3,
text: "Clean gecko tank",
completed: false
},
{
id: 4,
text: "Mow lawn",
completed: true
},
{
id: 5,
text: "Catch up on Arrested Development",
completed: false
}
]
export default todosData
Actually the problem is you're mutating the callback parameter in handleChange
, it's generally highly recommended to avoid mutating them cause they lead to unexpected behavior.实际上问题是你正在改变handleChange
中的回调参数,通常强烈建议避免改变它们,因为它们会导致意外行为。 I'd rewrite like below:我会重写如下:
class App extends 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) return { ...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>;
}
}
You can check the result here: https://xd5w9.codesandbox.io/你可以在这里查看结果: https://xd5w9.codesandbox.io/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.