对象作为 React 子项无效(找到:具有键 {id, name} 的对象)。如果您打算呈现子集合,请改用数组

Objects are not valid as a React child (found: object with keys {id, name}). If you meant to render a collection of children, use an array instead

我想做的是从 API 中提取数据并使用 material-table library 在 table 中显示它。我相信是我没有设法以正确的方式操作对象和数组。

我的apireturns这个回复:

{
  "data": [
    {
      "id": 7,
      "field01": 1,
      "field02": 1,
      "field03": false,
      "people": {
        "id": 1,
        "name": "John"
      },
       "id": 8,
       "field01": 2,
       "field02": 2,
       "field03": false,
       "people": {
         "id": 2
         "name": "Mattew"
      },
    },
  ]
}

我用来从 api:

中提取数据的代码
const [data, setData] = useState([]);

  const getValues = async () => {
    await api.get("/myrequest")
      .then(response => {
        setData(response.data.data);

      }).catch(error => {
        console.log(error);
      })
  }

我使用material-table创建的table:

<MaterialTable
            columns={[
              { title: 'Field 01', field: 'field01' },
              { title: 'Field 02', field: 'field02' },
              { title: 'Field 03', field: 'field03' },
              { title: 'Field 04',field: 'people.name' },
            ]}
            data={data}
            title="My table"
          />

查看文档时我注意到了这一点:对象作为 React 子项无效(找到:具有键 {id, name} 的对象)。如果您打算呈现子项集合,请改用数组。

我认为错误是因为我的 api returns 数组和 table 无法识别。

但我还是没能做到。而我这样做的方式 returns 出现以下错误: 失败的道具类型:提供给 MaterialTable

的无效道具 data

好吧,您使用的包似乎无法处理嵌套对象,因此您有两个选择:

  • 考虑使用其他软件包,例如 react-table

https://github.com/tannerlinsley/react-table

  • 创建一个适配器以拥有包含平面对象的数组
const adapter = data => data.map(item => (
    {
        id: item.id,
        field01: item.field01,
        field02: item.field02,
        field03: item.field03,
        name: item.people.name,
    }
));

然后在你的组件中

<MaterialTable
    columns={[
        { title: 'Field 01', field: 'field01' },
        { title: 'Field 02', field: 'field02' },
        { title: 'Field 03', field: 'field03' },
        { title: 'Field 04',field: 'name' },
    ]}
    data={adapter(data)}
    title="My table"
/>

注:

您应该使用此字段来访问您的数据

response.data.data

因为,如您所写,response.data 有一个附加字段 data,其中包含您的对象数组。