【问题标题】:Refresh table not working with functional component - using MaterialTable from https://material-table.com刷新表不适用于功能组件 - 使用来自 https://material-table.com 的 MaterialTable
【发布时间】:2020-04-30 16:05:03
【问题描述】:

我使用 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(),但它不起作用。我怎样才能做到这一点?

【问题讨论】:

    标签: reactjs typescript material-ui react-functional-component


    【解决方案1】:

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

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

    然后

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

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

    【讨论】:

    • 这不是解决方案。 MaterialTable 有参数 'query' 我必须在这个片段中传递:``` data={query => fetchData(query, 'localhost:8080/products') } ``` 那他呢?
    • 我需要类似的解决方案:stackoverflow.com/questions/55752163/…,但适用于功能组件。
    • 哦。好的。也许保持其他状态,比如获取数据的时间戳?并在时间戳更改时重新渲染。不过,这似乎是一个绝望的想法:p
    猜你喜欢
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    相关资源
    最近更新 更多