Material UI DataGrid - 如何判断用户选择了哪些行?

时间:2021-03-09 21:04:38

标签: javascript reactjs material-ui

我正在使用 React 和 Material UI 创建网站。我想知道在我的 DataGrid 中选择了哪些行。

我想使用 useState 用当前选定的行填充一个数组。我正在 handleRowSelection 尝试这样做。

目前 e.selection 模型正在打印出正确的选定行,但是当我尝试将选定的行放入我的 useState 数组时,它会跳过第一个选定的行。

例如:如果我选择了第 2 行和第 4 行,e.selection 模型会将 ["2","4"] 打印到控制台,但 select 只会打印 ["4"]

我错过了什么?为什么 select 没有选择第一行?

import * as React from 'react';
import { DataGrid } from '@material-ui/data-grid';

const columns = [
  { field: 'id', headerName: 'ID', width: 70 },
  { field: 'firstName', headerName: 'First name', width: 130 },
  { field: 'lastName', headerName: 'Last name', width: 130 },
  {
    field: 'age',
    headerName: 'Age',
    type: 'number',
    width: 90,
  },
  {
    field: 'fullName',
    headerName: 'Full name',
    description: 'This column has a value getter and is not sortable.',
    sortable: false,
    width: 160,
    valueGetter: (params) =>
      `${params.getValue('firstName') || ''} ${params.getValue('lastName') || ''}`,
  },
];

const rows = [
  { id: 1, lastName: 'Snow', firstName: 'Jon', age: 35 },
  { id: 2, lastName: 'Lannister', firstName: 'Cersei', age: 42 },
  { id: 3, lastName: 'Lannister', firstName: 'Jaime', age: 45 },
  { id: 4, lastName: 'Stark', firstName: 'Arya', age: 16 },
  { id: 5, lastName: 'Targaryen', firstName: 'Daenerys', age: null },
  { id: 6, lastName: 'Melisandre', firstName: null, age: 150 },
  { id: 7, lastName: 'Clifford', firstName: 'Ferrara', age: 44 },
  { id: 8, lastName: 'Frances', firstName: 'Rossini', age: 36 },
  { id: 9, lastName: 'Roxie', firstName: 'Harvey', age: 65 },
];

export default function DataGridDemo() {

 const [select, setSelection] = useState([]);

    const handleRowSelection = (e) => {
       
       // prints correct indexes of selected rows
        console.log(e.selectionModel);
        
        // missing the first row selected
        setSelection(e.selectionModel);
        console.log(select);

    }

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid 
      rows={rows} 
      columns={columns} 
      pageSize={5} 
      checkboxSelection 
      NoRowsOverlay
      onSelectionModelChange = {handleRowSelection}
      />
    </div>
  );
}

1 个答案:

答案 0 :(得分:0)

设置状态变量是一种异步方法。

这就是 useEffect 出现的地方。 useEffect 意味着在发生变化时产生副作用。所以

const handleRowSelection = (e) => {
  setSelection(e.selectionModel);
  console.log(select); // <-- The state is still not updated
}

但是

const handleRowSelection = (e) => {
  setSelection(e.selectionModel);
}

useEffect(() => {
  console.log(select); // <-- The state is updated
}, [select]);

https://codesandbox.io/s/charming-sutherland-9ryyt

请注意 useEffect 回调在组件加载后也被调用(因为 select 已更改),但在这种情况下这无关紧要,因为它作为空数组启动 - 尚未选择任何内容.

相关问题