切换布尔值反应

时间:2020-10-09 06:11:00

标签: javascript reactjs

为什么这不起作用?如果我console.log todo.completed,它会更改,但会再次更改为原始值。

handleChange(id) {
  this.setState(prevState => {
    const updatedTodos = prevState.todos.map(todo => {
      if (todo.id === id) {
        todo.completed = !todo.completed
      }
      return todo // Puts todo item in updatedTodos array in the same index
    })
    return {
      todos: updatedTodos
    }
  })
}

2 个答案:

答案 0 :(得分:1)

这是因为您正在对对象进行突变,这会导致反应不良并导致意外结果

handleChange(id) {
    this.setState(prevState => {
    const updatedTodos = prevState.todos.map(todo => {
        if (todo.id === id) {
            // todo.completed = !todo.completed
            //mutating, when mutating react doesn't understand it's a new entity

            //you have to create a new object based on the todo and change the props as you want
            return {
                ...todo,
                completed: !todo.completed
            }
        }
        return todo // Puts todo item in updatedTodos array in the same index
    })
    return {
        todos: updatedTodos
    }
    })
}

答案 1 :(得分:0)

您正在直接更改todo对象,这可能导致奇怪的行为。

您将希望返回一个新的待办事项,而不是根据您的状况更改待办事项。

返回{...待办事项,已完成:!todo.completed}

更多详细信息,请点击https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#updating-an-item-in-an-array