0

我使用来自https://material-table.com/#/docs/features/editable的MaterialTable在我的应用程序中显示数据和 crud 操作。我想在 CRUD 操作(添加、更新、删除)之后刷新表中的数据。

function fetchData(query: Query<Row>, fetchUrl: String): Promise<QueryResult<never>> {
  return (new Promise((resolve, reject) => {
    let url = `${fetchUrl}?page=${query.page}&size=${query.pageSize}`
    fetch(url, {
      headers: {
        'Content-Type': 'application/json',
        'accept': 'application/json',
        'Authorization': `Bearer ${getSessionStorageItem('token')}`
      }
    })
      .then(response => response.json())
      .then(result => {
        resolve({
          data: result.content,
          page: result.pageable.pageNumber,
          totalCount: result.totalElements,
        })
      })
  })
  )
}

export function MaterialTableDemo() {

  return (
    <MaterialTable
      title="Produkty"
      localization={{
        header: {
          actions: "Akcje"
        }
      }}
      columns={[
        { title: 'Id', field: 'id', editable: 'never' },
        { title: 'Nazwa', field: 'name' },
        { title: 'Cena', field: 'price' },
      ]}
      data={query =>
        fetchData(query, 'http://localhost:8080/products')
      }
      icons={tableIcons}
      editable={{
        onRowAdd: newData =>
          new Promise((resolve, reject) => {
            setTimeout(() => {
              addProducts(newData);
              resolve()
            }, 3000)
          }),
        onRowUpdate: (newData, oldData) =>
          new Promise((resolve, reject) => {
            setTimeout(() => {
              updateProducts(newData);
              resolve()
            }, 600)
          }),
        onRowDelete: oldData =>
          new Promise(resolve => {
            setTimeout(() => {
              deleteProduct(oldData.id);
              resolve();
            }, 6000);
          }),
      }}
    />
  );
}

我尝试使用 React 中的 createRef() 但它不起作用。我怎样才能做到这一点?

4

1 回答 1

0

您是否尝试过将下载的数据保持在状态?

const [tableData, setTableData] = useState([])

然后

useEffect(() => {
  // Your download function
  setTableData(response.data)
}, [])

它应该强制 React 监视这些数据并在有任何变化时重新渲染组件。

于 2020-01-13T22:48:21.600 回答