数据网格组件要求所有行都具有唯一的 `id` 属性

问题描述 投票:0回答:6

我知道我必须使用 getRowId,但是我如何使用

statId
来反对
id
?它是独一无二的。或者为它们中的每一个生成一个
id
属性?

错误:MUI:数据网格组件要求所有行都具有唯一的

id
属性。 或者,您可以使用
getRowId
属性为每一行指定自定义 id。 在 rows 属性中提供了没有 id 的行: {"statId":813183,"teamId":3,"season":2021,"name":"亚特兰大老鹰队","team":"ATL","wins":41,"losses":31,"fieldGoalsMade ":3492.1,"fieldGoalsAttempted":7468.1,"fieldGoalsPercentage":55.6,"twoPointersMade":2427.9,"twoPointersAttempted":4612.1,"twoPointersPercentage":62.5,"threePointersMade":1064.2,"threePointersAttempted":2856,"threePointersPercentage": 44.3,“freeThrowsMade”:1684.8,“freeThrowsAttempted”:2074.8,“freeThrowsPercentage”:96.5,“offensiveRebounds”:903.6,“defensiveRebounds”:3002.2,“rebounds”:3905.9,“assists”:2065.3,“steals”:598.1, "blockedShots":405.4,"turnovers":1086.7,"personalFouls":1655.1,"points":9733.2,"doubleDoubles":120.1,"tripleDoubles":1.4}

import { useState, useEffect } from 'react';
import type { NextPage } from 'next';
import Container from '@mui/material/Container';
import Box from '@mui/material/Box';
import { DataGrid, GridColDef, GridRowIdGetter } from '@mui/x-data-grid';
import { Grid, Paper, Typography } from '@mui/material';
import Skeleton from '@mui/material/Skeleton';
import { blue } from '@mui/material/colors';

import FormOne from './../src/FormOne';
import { TeamSeason } from './../src/lib/interfaces/TeamSeason';

const LoadingSkeleton = () => (
  <Box
    sx={{
      height: 'max-content',
    }}
  >
    {[...Array(10)].map((_, index) => (
      <Skeleton variant="rectangular" sx={{ my: 4, mx: 1 }} key={index} />
    ))}
  </Box>
);

const columns: GridColDef[] = [
  { field: 'statId', headerName: 'Stat ID' },
  { field: 'name', headerName: 'Name', width: 300 },
  { field: 'season', headerName: 'Season', width: 600 },
];

const Home: NextPage = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setInterval(
      () =>
        fetch('https://localhost:7000/TeamSeason/2021')
          .then((response) => response.json())
          .then((data) => {
            setData(data);
            setLoading(false);
          }),
      3000
    );
  }, []);

  return (
    <Container
      maxWidth={false}
      sx={{
        height: '100vh',
        overflow: 'auto',
        background: `linear-gradient(to right, ${blue[200]}, ${blue[500]})`,
      }}
    >
      <Container maxWidth="lg" sx={{ mt: 3, mb: 3 }}>
        <Grid container spacing={{ xs: 2, md: 3 }}>
          <Grid item xs={12} md={6}>
            <Paper sx={{ padding: 3 }}>
              <FormOne data={data} />
            </Paper>
          </Grid>

          <Grid item xs={12} md={6}>
            <Paper sx={{ padding: 3 }}></Paper>
          </Grid>

          <Grid item xs={12}>
            <Paper sx={{ padding: 3 }}>
              <DataGrid
                sx={{ height: '650px' }} // either autoHeight or this
                rows={data}
                columns={columns}
                pageSize={10}
                // autoHeight
                rowsPerPageOptions={[10]}
                disableSelectionOnClick
                disableColumnMenu
                disableColumnSelector
                components={{
                  LoadingOverlay: LoadingSkeleton,
                }}
                loading={loading}
              />
            </Paper>
          </Grid>
        </Grid>
      </Container>
    </Container>
  );
};

export default Home;

export interface TeamSeason {
  statId: number;
  teamId: number;
  season: number;
  name: string;
  team: string;
  wins: number;
  losses: number;
  fieldGoalsMade: number;
  fieldGoalsAttempted: number;
  fieldGoalsPercentage: number;
  twoPointersMade: number;
  twoPointersAttempted: number;
  twoPointersPercentage: number;
  threePointersMade: number;
  threePointersAttempted: number;
  threePointersPercentage: number;
  freeThrowsMade: number;
  freeThrowsAttempted: number;
  freeThrowsPercentage: number;
  offensiveRebounds: number;
  defensiveRebounds: number;
  rebounds: number;
  assists: number;
  steals: number;
  blockedShots: number;
  turnovers: number;
  personalFouls: number;
  points: number;
  doubleDoubles: number;
  tripleDoubles: number;
}

reactjs typescript material-ui next.js datagrid
6个回答
15
投票

你可以在

DataGrid
道具中使用它:

<DataGrid getRowId={(row) => row.statId}/>

8
投票

有了这个错误,请记住迭代在

keys
上运行以充当每行的唯一标识符。
getRowId
属性希望从行中推断出一个唯一的 id。

这是一个示例解决方案:

const columns: GridColDef[] = [
      { salary:53025, first_name:"Don" },
      { salary:63026, first_name:"Ted" },
      { salary:73027, first_name:"Bill" },
      { salary:83028, first_name:"Al" },
      { salary:23022, first_name:"Biff" },
   ];

   return (
      <div style={{ height: 300, width: "100%" }}>
         <DataGrid
            rows={rows}
            columns={columns}
            getRowId={(row: any) =>  row.first_name + row.salary}
         />
      </div>

或者如果您仍然有按键碰撞,您可以尝试这样的事情

function generateRandom() {
    var length = 8,
        charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
        retVal = "";
    for (var i = 0, n = charset.length; i < length; ++i) {
        retVal += charset.charAt(Math.floor(Math.random() * n));
    }
    return retVal;
}

   return (
      <div style={{ height: 300, width: "100%" }}>
         <DataGrid
            rows={rows}
            columns={columns}
            getRowId={(row: any) =>  generateRandom()}
         />
      </div>

可以在 MUI 网站上找到更多信息


5
投票

如果你使用的是 MongoDB,你应该包括这一行

getRowId={(row) => row._id}
因为 MongoDB 的 ID 被命名为 _id 这将查找 _id 选项并选择它作为唯一 ID


3
投票

Datagrid 需要一个 id 所以你需要名为“id”的列所以

(row) => ({id:statId})

2
投票

这意味着您的响应对象列表没有 id 属性,从您的数据中找到任何 uniq 键并用作 id。示例-

<DataGrid rows={dataFromBackend} 
columns={columns} 
getRowId={(row: any) => row.uniqKeyfromBackend} 
/>

0
投票

我从数据库 MongoDB 获取数据,所以这对我有用

  <DataGrid
    rows={usersData}
    disableSelectionOnClick
    columns={columns}
    pageSize={8}
    checkboxSelection
    getRowId={(row) => row._id}
    >
© www.soinside.com 2019 - 2024. All rights reserved.