我制作了一个待办事项应用程序,如果选中“显示已完成的任务”,我想通过显示所有已完成的任务来即兴创作
选中“显示已完成的任务”效果很好,但取消选中它不会执行“else 语句”。
最初想要的是,如果它未经检查,它应该给我所有的状态,无论是否完成。
“else 语句”中的代码仅用于调试。它至少应该给我数组[0]和数组[2],尝试控制台记录它,它抛出一个未定义的错误。
PS:尝试在取消选中时控制台记录某些内容,未选中正在工作。
filterCompleted = (e) => {
if(e.target.checked){
this.setState({todos: [...this.state.todos.filter(todo => {return todo.completed === true})]})
}
else{
//code below just for debugging but this does not execute
this.setState({todos: [...this.state.todos.filter(todo => {return todo.completed === false})]})
}
}
最佳答案
这只会在第一次起作用,除此之外,状态只会保存所有已完成的任务或所有未完成的任务。
你应该引入一个新的状态,例如
constructor(prop) {
this.state = {
todos: [],
filterCompleted: false
}
}
...
filterCompleted = e => this.setState({ filterCompleted: e.target.checked })
然后,在呈现列表时,您可以简单地排除未完成
的项目,例如
const items = this.state
.todos
.filter(x => !this.state.filterCompleted || x.completed)
.map(x => <TodoItem {...x} />)
关于javascript - 取消选中reactjs中的复选框不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59354153/