簡體   English   中英

當道具從父項更改時,我的子項復選框未更新嗎?

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

這是我的父組件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。 您可以在待檢查的待辦事項道具上看到我使用的將其設置為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調試器上檢查為true,但不會重新渲染,它僅在我選中另一個框時才重新渲染,將檢查我檢查的最后一個而不是最新的?

您需要刪除()圍繞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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM