Error: MUI: The data grid component requires all rows to have a unique `id` property

Error: MUI: The data grid component requires all rows to have a unique `id` property

所以我正在尝试使用来自 API:

的数据填充数据网格
    const [listofInvoices, setListofInvoices] = useState({id: 0})
useEffect(()=>{
    axios.get("http://localhost:3001/invoices").then((response)=>{
        setListofInvoices(response.data) //State which contains the response from the API request
    });
  }, [])
 const rows: GridRowsProp = [listofInvoices];
 const columns: GridColDef[] = [
    { field: "invNumber", headerName: "Invoice Number", width: 150 },
    { field: "invAmount", headerName: "Invoice Amount", width: 150 }
  ];

然后我使用此代码显示 DataGrid:

    <div style={{margin:'auto', height: 450, width: '95%' }}>
  <DataGrid rows={rows} columns={columns} getRowId={(row) => row.id} components={{ Toolbar: GridToolbar }} />
</div>

但是即使我的所有行都有一个 ID,我仍然会收到此错误: Console Error

我怀疑您混淆了数组和对象。这里将“发票列表”初始化为单个对象(不是列表):

const [listofInvoices, setListofInvoices] = useState({id: 0})

为了弥补它不是数组这一事实,你用它制作了一个数组:

const rows: GridRowsProp = [listofInvoices];

然后将生成的数组传递给组件。哪个有效。但是,在 AJAX 操作之后,您更新了状态:

setListofInvoices(response.data)

response.data只是另一个对象,还是数组(如URL“发票”所暗示的)?如果它是一个数组,那么你仍然补偿它不是一个数组:

const rows: GridRowsProp = [listofInvoices];

这意味着现在您要向组件传递一个包含一个元素的数组,并且该元素也是一个数组,而数组没有 id 属性.


首先解决语义问题。使单数事物保持单数,使复数事物保持复数。否则你只会让自己陷入混乱。将“发票清单”设为实际清单:

const [listofInvoices, setListofInvoices] = useState([{id: 0}])

那么你就不必补偿它不是数组:

const rows: GridRowsProp = listofInvoices;

并且任何时候更新状态,只要“发票列表”仍然是一个数组,那么它在语义上仍然是复数并且仍然是正确的。这样你总是拥有一个数组,而不是有时是一个对象,有时是一个数组,有时是一个数组数组。