如何在CRUD操作后重新呈现/更新反应中的表?

问题描述 投票:0回答:2

我已经使用了简单的表(下面附加的代码),并试图寻找许多参考,但无法找到适合我的问题的解决方案。表格显示正常,但是在添加,更新或删除任何数据时问题就会出现。除非刷新页面,否则不会反映出来。我尝试过的几种方法是更新状态,但没有帮助。我甚至尝试过有力地更新组件但是徒劳无功。我甚至尝试渲染组件。

<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});
  });
}
reactjs html-table crud page-refresh rerender
2个回答
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


0
投票

工作得很好。在添加/更新或删除条目的响应之前调用API以显示列表是错误的。最重要的是,如果状态得到更新,组件将重新渲染自身。只需要小心,不要像我一样搞乱API调用。

© www.soinside.com 2019 - 2024. All rights reserved.