[英]My child component checkbox is not updating when props changed from the parent?
This is the code from my parent component TodoList: 这是我的父组件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. 当选中Todo组件中的复选框时,我在TodoList组件的状态上添加了checkedIds。 You can see on the checked prop on todo that I use includes to set it to true or false.
您可以在待检查的待办事项道具上看到我使用的将其设置为true或false的情况。 But my problem is my child component doesn't update and I am using componentWillReceiveProps.
但是我的问题是我的子组件没有更新,并且我正在使用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? 一切正常,当单击时在React调试器上检查为true,但不会重新渲染,它仅在我选中另一个框时才重新渲染,将检查我检查的最后一个而不是最新的?
You need to remove the ()
around this.state.checkedIds.includes(todo.id)
. 您需要删除
()
围绕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.