【问题标题】:Error: MUI: The data grid component requires all rows to have a unique `id` property错误:MUI:数据网格组件要求所有行都具有唯一的“id”属性
【发布时间】:2022-10-15 02:46:14
【问题描述】:

所以我正在尝试使用我的 API 中的数据填充 Datagrid:

    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

【问题讨论】:

    标签: reactjs material-ui datagrid


    【解决方案1】:

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

    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;
    

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

    【讨论】:

    • 这是一个完美的男人。您不仅帮我解决了我的问题,而且还向我解释了它,以便我能够完全理解出了什么问题以及如何避免将来再次犯同样的错误。传奇!!
    【解决方案2】:

    在 MUI DataGrid 上使用 getRowId 属性 来自官方链接和参考:getRowId type =func
    返回给定 GridRowModel 的 id。 official MUI Grid API link getRowId={(row) =&gt; row.ticket_serialNo}

    const gridColumn = [{
      field: "ticket_serialNo",
      headerName: "Ticket Id",
      headerClassName: "super-app-theme--header",
      type: "string",
      headerAlign: "left",
      flex: 1,
    },
    {
      field: "ticketState",
      headerClassName: "super-app-theme--header",
      headerName: "State",
      headerAlign: "left",
      flex: 1,
    },
    {
      field: "ticketCity",
      headerClassName: "super-app-theme--header",
      headerName: "City",
      headerAlign: "left",
      flex: 1,
    },]
    

    【讨论】:

      猜你喜欢
      • 2022-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      相关资源
      最近更新 更多