[英]React setState not updating the state
I'm new to React and I'm having some trouble with changing sate with setState
method.我是 React 的新手,在使用
setState
方法更改状态时遇到了一些麻烦。 I'm trying to update state of ToDo item when I click on the checkbox.单击复选框时,我正在尝试更新 ToDo 项目的 state。 When I'm debugging
handleChange
method it changes the state of the item for a while.当我调试
handleChange
方法时,它会暂时更改项目的 state。 Unfortunatelly, the final state is like at the beginning (state of the checkbox is never changed).不幸的是,最后的 state 就像开头一样(复选框的状态永远不会改变)。 Does somebody know where the problem is?
有人知道问题出在哪里吗?
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} todoItem={item}
handleChange={this.handleChange}/>)
return (
<div className="App">
{todoItems}
</div>
);
}
}
export default App;
Here is my ToDoItem component:这是我的 ToDoItem 组件:
import React from 'react'
function ToDoItem(props){
return (
<div className = "todo-list">
<div className = "todo-item">
<input type="checkbox"
checked={props.todoItem.completed}
onChange = {() => props.handleChange(props.todoItem.id)}/>
<p>{props.todoItem.text}</p>
</div>
</div>
)
}
export default ToDoItem
Just use this handler and let me know if works.只需使用此处理程序,让我知道是否有效。
handleChange(id){
const list = this.state.todos.slice();
const index = list.findIndex(o => o.id === id);
list[index].completed = !list[index].completed;
this.setState({ todos: list });
}
I think the problem is here:我认为问题出在这里:
handleChange(id){
this.setState(prevState => {
const updatedTodos = prevState.todos.map(todo => {
if (todo.id === id) {
todo.completed = !todo.completed
}
return { ...todo }; // need to return a new object
})
return {
todos: updatedTodos
}
})
}
todo
s are objects and event if todos
are being set as a new object every time, its items referencing to the same object, and it is used by ToDoItem
. todo
是对象和事件,如果 todo 每次都被设置为新的todos
,它的项目引用相同的 object,并且它被ToDoItem
使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.