我正在使用 React 和 Material UI 创建一个网站。我想知道在我的 DataGrid
中选择了哪些行。
我想使用 useState 用当前选定的行填充一个数组。我试图在 handleRowSelection
中这样做。
目前 e.selection 模型正在打印出正确的选定行,但是当我尝试将选定的行放入我的 useState
数组时,它会跳过第一个选定的行。
例如:如果我选择了第 2 行和第 4 行,e.selection
模型将打印 ["2","4"]
到控制台,但选择只会打印 ["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>
);
}
最佳答案
设置状态变量是一种异步方法。
这就是 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
已被更改)但在这种情况下无关紧要,因为它以空的形式启动数组 - 尚未选择任何内容。
关于javascript - Material UI DataGrid - 如何判断用户选择了哪些行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66554762/