【发布时间】:2023-01-10 06:02:04
【问题描述】:
我正在尝试使用示例 here 添加来自 @mui/x-data-grid 的 selectedRow 功能以返回选定行中的所有数据。在演示中,他们使用 useDemoData mod 来填充表格,而我使用 Axios 调用我的 API 来填充行并使用预配置的列。
import React, { useState, useEffect } from 'react';
import axios from "axios";
import { DataGrid, GridToolbar } from '@mui/x-data-grid';
const columns = [
{ field: 'id', headerName: 'Job ID', width: 170 },
{ field: 'file_name', headerName: 'File Name', width: 250 },
{ field: 'product_type', headerName: 'Product Type', width: 300 },
{ field: 'status', headerName: 'Status', width: 170, editable: true },
];
function QueueMgrTable() {
const [data, setData] = useState([]);
const [loadingData, setLoadingData] = useState(true);
const [selectedRows, setSelectedRows] = useState([]);
async function getData() {
await axios
.get('https://myendpoint.com/test/jobs', {
headers: {
'Content-Type': 'application/json'
}
})
.then((response) =>{
var test_data = response.data.data;
setData(
test_data.map((x) => {
return {
id: parseInt(`${x.job_id}`),
file_name: `${x.file_name}`,
product_type: `${x.product_type}`,
status: `${x.status}`
}
})
);
setLoadingData(false);
});
}
useEffect((data) => {
console.log(config);
getData();
if (loadingData) {
getData();
}
}, []);
return (
<div style={{ height: 600, width: '100%' }}>
{loadingData ? (
<p>Loading. Please wait...</p>
) : (
<DataGrid
columns={columns}
pageSize={20}
rowsPerPageOptions={[10]}
checkboxSelection
components={{ Toolbar: GridToolbar }}
onSelectionModelChange={(ids) => {
const selectedIDs = new Set(ids);
const selectedRows = data.rows.filter((row) =>
selectedIDs.has(row.id),
);
setSelectedRows(selectedRows);
}}
rows={data}
/>
)}
<pre style={{ fontSize: 10 }}>
{JSON.stringify(selectedRows, null, 4)}
</pre>
</div>
);
};
export default QueueMgrTable;
当我点击上面的一行时,出现以下错误。关于我在这里做错了什么的任何建议或线索?我怀疑它在 data 由于某种原因由于状态而未定义时尝试使用过滤器。
【问题讨论】:
标签: reactjs react-hooks material-ui datagrid state