简体   繁体   English

我的简单反应 todoapp 的 handleChange 方法没有做它需要做的事情

[英]My handleChange method of simple react todoapp is not doing what it needs to do

In the output, Only the default completed values are checked.在 output 中,仅检查默认完成值。 not able change the checks of tasks.无法更改任务的检查。

These are my Java script files这些是我的 Java 脚本文件

app.js

class App extends Component {
  constructor() {
    super()
    this.state = {
      todos: Todosdata
    }
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(id) {
    this.setState(prevState => {
      const udpated = prevState.todos.map(todo => {
        if (todo.id === id) {
          todo.completed = !todo.completed
        }
        return todo
      })

      return {
        todos: udpated
      }
    })
  }
  render() {
    const todoelements = this.state.todos.map(item => <ToDoItem key={item.id}
      todoitem={item}
      handleChange={this.handleChange} />)

    return (
      <div className="App">
        < div className="todo-list" >
          {todoelements}
        </div >
      </div>
    )
  }
}
 

ToDoItem.js

const ToDoItem = (props) => {
    const Afterstyle = {
        fontColor: "red",
        textDecoration: "line-through"
    }

    return (
        <div className="todo-item">
            <input type="checkbox"
                checked ={props.todoitem.completed}
                onChange ={() => props.handleChange(props.todoitem.id)} />
            <p style={props.todoitem.completed ? Afterstyle : null}>{props.todoitem.task}</p>
        </div>
   )
}

i did console log inside if condition of handle Change method,its printing 2 times.如果句柄更改方法的条件,我做了控制台日志,它打印了 2 次。 I am stuck at this for hours please fix this!我被困了几个小时,请解决这个问题!

You are mutating the todo item instead of creating a new one.您正在改变todo而不是创建新的。 Change your handler like that:像这样更改您的处理程序:

handleChange(id) {
    this.setState(prevState => {
        const udpated = prevState.todos.map(todo => {
            if (todo.id === id) {
                // if the id matches return a new object
                return {...todo, completed: !todo.completed};
            }
        
            return todo
        });

        return {todos: udpated};
    }
}

Live Demo:现场演示:

编辑富有同情心的架构-kzsu2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM