reactjs 从API获取数据并将响应数据显示到数据网格中

epggiuax  于 2022-12-18  发布在  React
关注(0)|答案(1)|浏览(103)

尝试从API提取数据并将其传递给DataGrid时出错。
返回的数据如下:

{
  data: [{
      type: 'PropertyDamage',
      id: '100',
      attributes: {
        identification_number: '3931',
        damage_date: '2021-04-29',
        report_date: '2021-06-26'
      }
    },
    {
      type: 'PropertyDamage',
      id: '101',
      attributes: {
        identification_number: '3839',
        damage_date: '2021-01-21',
        report_date: '2021-08-25'
      }
    },
    {
      type: 'PropertyDamage',
      id: '102',
      attributes: {
        identification_number: '3735',
        damage_date: '2021-04-25',
        report_date: '2021-10-29'
      }
    }
  ]
}

处理数据提取以及呈现DataGrid的组件:

const columns = [
  { field: "id", headerName: "ID" },
  { field: "type", headerName: "TYPE" },
];

const Dashboard = () => {

  const [propertydamages, setPropertyDamages] = useState([]);

  useEffect(() => {
    const url = "URL";
    fetch(url, {
      method: "GET",
      withCredentials: true,
      headers: {
        "X-API-Key": "API Key",
      },
    })
      .then((response) => response.json())
      .then((json) => {
        setPropertyDamages(json);
      })
      .catch(function (error) {
        console.log(error);
      });
  }, []);

  return (
    <Box m="20px">
      {/* Data Grid */}
      <DataGrid rows={propertydamages} columns={columns} />
    </Box>
  );
};

渲染时记录到控制台的错误:

index.js:1272 Warning: Failed prop type: Invalid prop `rows` of type `object` supplied to `ForwardRef(DataGrid)`, expected an array.
        at div
        at http://localhost:3000/static/js/0.chunk.js:942:73
        at Box (http://localhost:3000/static/js/0.chunk.js:69597:74)
        at div
        at http://localhost:3000/static/js/0.chunk.js:942:73
        at Box (http://localhost:3000/static/js/0.chunk.js:69597:74)
        at Dashboard (http://localhost:3000/static/js/main.chunk.js:373:77)
        at RenderedRoute (http://localhost:3000/static/js/0.chunk.js:153998:27)
        at Routes (http://localhost:3000/static/js/0.chunk.js:154437:24)
        at main
        at div
        at InnerThemeProvider (http://localhost:3000/static/js/0.chunk.js:68080:72)
        at ThemeProvider (http://localhost:3000/static/js/0.chunk.js:67042:24)
        at ThemeProvider (http://localhost:3000/static/js/0.chunk.js:68098:24)
        at App (http://localhost:3000/static/js/main.chunk.js:51:72)
        at Router (http://localhost:3000/static/js/0.chunk.js:154367:30)
        at BrowserRouter (http://localhost:3000/static/js/0.chunk.js:152656:23)


我尝试将数据更改为不同的格式,但没有效果。

zphenhs4

zphenhs41#

对于那些读过这篇文章的人,MUI数据网格接受rows属性中的对象数组

<DataGrid rows={propertydamages} columns={columns} />

将此属性设置为nullundefinedobject将导致错误,并且组件将不会呈现。如果使用状态填充行,确保初始值是空数组[],并且正在接收的数据实际上将是数组。如何执行检查由您决定,但我强烈建议不要更新状态,除非更新将导致阵列

相关问题