Material Table React 上的选择和远程数据分页

Selection and Remote Data Pagination on Material Table React

我需要帮助我使用 material-table 对我的数据做出反应 table。我想同时使用 selection 和分页,但问题是如果我 select 某一行并将页面和 return 更改为上一页。它没有 select 那一行。这是我创建的示例片段。是否可以覆盖 selection 道具?

const Table = () => {
const [selectedRows, setSelectedRows] = useState([]);

function handleSelectChange(rows) {
setSelectedRows(rows)
}
return (
<MaterialTable
      title="Remote Data Preview"
      columns={[
        {
          title: 'Avatar',
          field: 'avatar',
          render: rowData => (
            <img
              style={{ height: 36, borderRadius: '50%' }}
              src={rowData.avatar}
            />
          ),
        },
        { title: 'Id', field: 'id' },
        { title: 'First Name', field: 'first_name' },
        { title: 'Last Name', field: 'last_name' },
      ]}
      options={{
        selection:true,
      }}
      onSelectionChange={(rows) => handleSelectChange(rows)}
      data={query =>
        new Promise((resolve, reject) => {
          let url = 'https://reqres.in/api/users?'
          url += 'per_page=' + query.pageSize
          url += '&page=' + (query.page + 1)
          fetch(url)
            .then(response => response.json())
            .then(result => {
              resolve({
                data: result.data,
                page: result.page - 1,
                totalCount: result.total,
              })
            })
        })
      }
    />
)
}

我已经创建了一个问题将把它作为参考。 https://github.com/mbrn/material-table/issues/1189

由于您已经知道选定的行,因此您只需像这样修改获取的数据:

data: result.data.map(row => selectedRows.find(selected => selected.id === row.id) ? { ...row, tableData: { checked: true } } : row)

这会将 tableData.checked 键添加到获取的数据中,并将其显示为选中状态。

这里是codesandbox.

此解决方案仅在您不 select 新页面上的另一行时有效,因为来自 onSelectionChange 的新 rows 将覆盖来自 select 的现有行前几页。为了能够跨页面 select 行,我更改了 handleSelectionChange 函数以首先检查当前 selectedRows 是否包含在显示的数据中,对于那些不包含的,我将其传播到 setState打电话。

function handleSelectionChange(rows) {
    const displayedIds = data.results.map(result => result.id)
    const selectedRowsNotDisplayed = selectedRows.filter(selectedRow => {
        return !displayedIds.includes(selectedRow.id)
    })

    setSelectedRows([...selectedRowsNotDisplayed, ...rows])
}