我已经使用了简单的表格(下面附加的代码),并尝试寻找许多参考资料,但无法找到适合我的问题的解决方案。表格显示正常,但是在添加,更新或删除任何数据时问题就会出现。除非刷新页面,否则它不会被反映出来。我尝试过的几种方法是更新状态,但没有帮助。我甚至尝试过有力地更新组件但是徒劳无功。我甚至试过渲染组件。
<div className="table">
<table className="table table-striped table-padding">
<thead>
<tr className="heading">
<th className="col-md-2">Image</th>
<th className="col-md-3">Office Name</th>
<th className="col-md-5">Address</th>
<th className="col-md-1"></th>
<th className="col-md-1"></th>
</tr>
</thead>
<tbody>
{
(this.state.dataUpdated) &&
this.state.data.map((list, index) => {
return (
<tr key={index}>
<td><img style={{height: '30px', width: '30px'}} src={list.imageData} alt="icon"/></td>
<td>{list.name}</td>
<td>{list.address}</td>
<td><button type="button" onClick={(e) => this.handleEdit(list.officeId)}><i className="fa fa-pencil" aria-hidden="true"></i></button></td>
<td><button type="button" onClick={(e) => this.handleDelete(list.officeId)}><i className="fa fa-trash" aria-hidden="true"></i></button></td>
</tr>
)
})
}
</tbody>
</table>
</div>
handleEdit(id) {
this.state.data.map(row => {
if(row.officeId === id) {
return (
this.setState({ displayData: row })
)
}
});
this.displayOfficeList();
}
handleDelete(id) {
const { dispatch } = this.props;
dispatch(commonActions.deleteOffice(id));
this.displayOfficeList();
}
displayOfficeList() {
this.toggleFlag();
commonServices.getOfficeList().then((res) => {
let demo = res;
this.setState({ data: demo.content});
this.setState({ dataUpdated: true});
});
}
答案 0 :(得分:0)
每次执行添加,编辑和删除等操作时,都需要更新数据状态。
使用componentWillReceiveProps,使用以下链接作为参考
React doesn't reload component data on route param change
您可以在此处找到官方文档https://reactjs.org/docs/state-and-lifecycle.html
还有 https://hackernoon.com/reactjs-component-lifecycle-methods-a-deep-dive-38275d9d13c0
答案 1 :(得分:0)
工作得很好。在添加/更新或删除条目的响应之前调用API以显示列表是错误的。最重要的是,如果状态得到更新,组件将重新渲染自身。只需要小心,不要像我那样搞乱API调用。