javascript - How to refresh mapped table in React?
问题描述
I am rendering a table from mapped elements stored in the React state. However, the tr row elements are not rendered in the tbody component, even though console commands show the data is there. The code to render table rows from this.state.tableData
is:
componentWillMount() {
let data = this.props.dbPersons.get("directory");
this.setState({ tableData: data });
}
...
renderTableData() {
return this.state.tableData.map((student, index) => {
const { id, person } = student;
console.log("id'", id);
console.log("person.lastName", person.lastName);
return (
<tr key={index}>
<td>{id}</td>
<td>{person.lastName}</td>
</tr>
)
})
}
tbody is rendered if tableData is stored in the state:
{this.state.tableData && <tbody>
{this.renderTableData()}
</tbody>}
But when the page is opened, the console displays the row data but tbody is rendered without any rows. Why? Does the component need to be refreshed somehow? Has the tbody component already been rendered and cannot be updated?
解决方案
除了导致警告的 componentWillMount(将其替换为 compontDidMount)之外,到目前为止您发布的代码没有任何问题。我看不出它会记录但不渲染的原因。这是您的代码的工作示例:
class App extends React.Component {
state = { tableData: false };
componentWillMount() {
setTimeout(
() =>
this.setState({
tableData: [{ id: 1 }, { id: 2 }],
}),
500
);
}
renderTableData() {
return this.state.tableData.map((student, index) => {
const { id } = student;
console.log('id', id);
return (
<tr key={index}>
<td>{id}</td>
{/* <td>{name}</td> removed this but still can see id*/}
</tr>
);
});
}
render() {
return (
<table>
{this.state.tableData && (
<tbody>{this.renderTableData()}</tbody>
)}
</table>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
也许你可以提供一个最小的例子来展示你正在经历的行为。
推荐阅读
- java - 请问RSocket世界中@ExceptionHandler的等价物是什么?
- c# - C# Roslyn CompletionService 在哪里获取方法重载信息
- python - 在训练/动态正则化期间更改 keras 正则化器
- html - Bootstrap 4拉伸列的背景以填充没有容器流体的屏幕宽度并与网格保持对齐
- javascript - 从打字稿中的对象列表中查找键的唯一值的高效方法
- powershell - PowerShell:唯一的对象数组
- r - 插入符号如何拆分 trainControl 中的数据?
- c++ - c++ operator[uint] msvc x86 构建失败,构建正常 x64
- node.js - 如何编辑从 multer 返回的路径以删除特定的单词?
- typescript - 您将如何使用 lambda 简化这段代码?