当从父级更改道具时,我的子组件复选框不会更新?

时间:2017-06-05 21:42:36

标签: javascript reactjs checkbox

这是我父组件TodoList的代码:

_handleSelectedTodo(e) {
    e.preventDefault(); 
    this.setState({checkedIds: [...this.state.checkedIds, e.target.value]});
  }
//render() { ...
  <ul>
    {todos.map((todo,todoIndex) => 
      <Todo
        key={todo.id}
        {...todo} // pass all the todo property
        onClick={() => onTodoClick(todo.id)}
        onTrashClick={() => onDeleteClick(todoIndex)}
        handleSelectedTodo = {this._handleSelectedTodo}
        checked={(this.state.checkedIds.includes(todo.id))}
      />
    )}
  </ul>

当选中Todo组件中的复选框时,我在TodoList组件的状态上添加了checkedIds。您可以在todo上检查我所使用的包括将其设置为true或false。但我的问题是我的子组件没有更新,我正在使用componentWillReceiveProps。这是代码:

constructor(props){
    super(props);
    this.state= { checked: false }
  }

  componentWillReceiveProps(nextProps) {
  this.setState({ checked: nextProps.checked });  
}
// render() { ...
<input
   checked={this.state.checked}
   onChange={handleSelectedTodo}
   type="checkbox"
   value={id}
></input>

它全部正常工作,当点击时,React调试器上的检查结果为真,但它不会重新呈现,只有在我检查另一个盒子时才会重新呈现,我检查的最后一个是否会被检查而不是最新的?< / p>

1 个答案:

答案 0 :(得分:0)

您需要移除()周围的this.state.checkedIds.includes(todo.id)

//render() { ...
  <ul>
    {todos.map((todo,todoIndex) => 
      <Todo
        key={todo.id}
        {...todo} // pass all the todo property
        onClick={() => onTodoClick(todo.id)}
        onTrashClick={() => onDeleteClick(todoIndex)}
        handleSelectedTodo = {this._handleSelectedTodo}
        checked={this.state.checkedIds.includes(todo.id)}
      />
    )}
  </ul>