Cannot add 属性 key, object is not extensible 错误 Apollo Client with antd

Cannot add property key, object is not extensible error Apollo Client with antd

我在使用 "@apollo/client": "^3.0.2" 和 ant design 时遇到错误 Cannot add property key, object is not extensible

我可以使用我的 graphql 查询从服务器成功获取数据,但是,问题是 return 对象中的数据不知何故不可扩展。在使用 apollo 客户端(使用 apollo boost)之前,这从来都不是问题。

为了让我的数据在ant design中的table中工作,我必须传入从服务器returned的data对象中获取的数组数据。我收到错误的部分是当我尝试遍历 items 数组,并向每个对象添加一个 key 时,这样反应就不会在控制台中抱怨缺少 key 元素用于 html.

  const items = [...data.items];
  console.log("items:", items);

  // Add a key for each item to make React stop complaining
  // Erorr occurs here!!!
  items.forEach(item => {
    item.key = item.id;
  });

有没有什么方法可以删除这种不必要的功能,这些功能阻碍了我们修改和扩展从服务器获得的结果的能力?我也尝试传播阵列制作深拷贝,但这也不起作用。

我需要做什么来确保我可以在每个数组项中添加一个额外的 key 字段,基于 id?

附录:

我实际上不需要执行 items.forEach() 操作的代码。但是,如果我不添加它,react 会抱怨 table 中的条目都缺少 key 值。这是我的解决方法,因为 ant design 中的 tables 从对象数组中获取数据,因此需要在其中有一个 key 值。由于从服务器查询数据通常不会在对象中包含 key 属性,因此必须手动添加。

设法通过 lodash 深度复制数组数据来弄清楚。

在返回的 data 对象上使用 _.cloneDeep(),即您正在查询的 object/table 的名称。

import * as _ from "lodash";
import { Table } from "antd";

function Component({ id, query }) {
  const { loading, error, data } = useQuery(query, {
    variables: { id }
  });

  if (loading) return <div />;
  if (error) return `Error! ${error}`;

  const items = _.cloneDeep(data.items);
  console.log("items:", items);

  // Add a key for each item to make React stop complaining
  items.forEach(item => {
    item.key = item.id;
  });

  return (
          <Table
            dataSource={items}
          />
  );