我有一个名为
dataTable
的反应变量,由 useState()
管理,它包含一个表格元素,作为 {dataTable}
嵌入在我网站的 HTML 中。
但是,当我用
setDataTable()
更新它时,它的值 确实 发生了变化,我可以用 console.log()
检查它,但由于某种原因它不会在 DOM 中更新。
以相同方式显示时,所有其他更简单的元素(例如数字变量)将在 DOM 中更新。
我用以下内容更新表格:
setDataTable(
<DataTable
todos={todos}
todoLogs={todoLogs}
deleteTodo={deleteTodo}
toggleTodo={toggleTodo}
></DataTable>
)
DataTable 类如下所示:
class DataTable extends React.Component {
constructor(props) {
super(props);
this.todos = props.todos;
this.todoLogs = props.todoLogs;
this.deleteTodo = props.deleteTodo;
}
render() {
const data = this.todoLogs;
// Map over the data to generate table rows
try {
const tableRows = data.map((todoLog) => (
<tr key={todoLog.id}>
<td>{this.todos.find(x => x.id === todoLog.id).title}</td>
<td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d09_04_24}></input></td>
<td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d08_04_24}></input></td>
<td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d07_04_24}></input></td>
<td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d06_04_24}></input></td>
<td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d05_04_24}></input></td>
<td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d04_04_24}></input></td>
<td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d03_04_24}></input></td>
<td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d02_04_24}></input></td>
<td><button><i className="material-icons" onClick={() => {this.deleteTodo(todoLog.id)}}>delete</i></button></td>
</tr>
));
return (
<table>
<thead>
<tr>
<th>Title</th>
<th>09/04</th>
<th>08/04</th>
<th>07/04</th>
<th>06/04</th>
<th>05/04</th>
<th>04/04</th>
<th>03/04</th>
<th>02/04</th>
</tr>
</thead>
<tbody>{tableRows}</tbody>
</table>
);
} catch (error) {
console.log(error);
return <p>Table Loading...</p>;
}
}
}
更新 React 组件或带有我不知道的参数的 HTML 元素有什么特别之处吗?
谢谢你。
您的组件未卸载/重新安装。因此 props 中的更改不会反映出来,因为您已将它们缓存在构造函数中。
无需缓存该组件的值。
因此,一种解决方案是直接使用道具。
class DataTable extends React.Component {
// no constructor
render(){
const {todoLogs:data, todos, deleteTodo} = this.props;
...
}
}
(所以实际上你根本不需要使用类,你可以使用函数组件)
另一种选择是使用
componentDidUpdate
并检查 prop 是否已更改,如果是,则更新本地缓存版本(您还应该对这些版本使用状态,而不是将它们直接存储在 this
上)。
最后,您可以在
key
组件上添加 DataTable
来触发卸载/重新挂载(不是最高效的方法)
setDataTable(
<DataTable
key={Date.now().toString()}
todos={todos}
todoLogs={todoLogs}
deleteTodo={deleteTodo}
toggleTodo={toggleTodo}
></DataTable>
)