简体   繁体   中英

My child component checkbox is not updating when props changed from the parent?

This is the code from my parent component 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>

when the checkbox in Todo component is checked I add checkedIds on the state of TodoList Component. You can see on the checked prop on todo that I use includes to set it to true or false. But my problem is my child component doesn't update and I am using componentWillReceiveProps. This is the code:

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>

It's all working and when clicked the checked is true on React debugger but it will not rerender, it only rerender if I check another box, the last one I checked will be checked and not the latest one?

You need to remove the () around 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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