簡體   English   中英

未捕獲的 TypeError:無效的解構不可迭代實例的嘗試

[英]Uncaught TypeError: Invalid attempt to destructure non-iterable instance

我正在使用 react-table 制作一個 DataTable 組件。 這是我的組件的代碼:

const DataTable: React.FC<IDataTable<any>> = (props: IDataTable<any>) => {
  const { columns, data, className, rowSelection, onChange, ...rest } = props;
  let tableColumns: HeaderColumn<any>[] = columns;
  useMemo(() => tableColumns, [rowSelection, columns]);
  const {
    getTableProps,
    headerGroups,
    rows,
    prepareRow,
    state: [{ selectedRows }],
  } = useTable({ columns: tableColumns, data }, useRowSelect);
  useEffect(() => onChange && onChange(selectedRows), [selectedRows]);
  return (
    <table {...getTableProps()} className={`ods-data-table ${className}`} {...rest}>
      <thead>
        {headerGroups.map((headerGroup, index) => (
          <tr key={index}>
            {headerGroup.headers.map((column, index) => (
              <th key={index} {...column.getHeaderProps()}>
                {column.render('Header')}
              </th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody>
        {rows.map(
          (row, i) =>
            prepareRow(row) || (
              <tr {...row.getRowProps()} tabIndex={i} key={i}>
                {row.cells.map((cell, i) => {
                  return (
                    <td {...cell.getCellProps()} key={i}>
                      {cell.render('Cell')}
                    </td>
                  );
                })}
              </tr>
            )
        )}
      </tbody>
    </table>
  );
};

當我嘗試使用此組件並傳遞數據時,我收到此錯誤:
“未捕獲的 TypeError:解構不可迭代實例的無效嘗試。為了可迭代,非數組對象必須具有 Symbol.iterator 方法。”
這是我嘗試將數據傳遞給 DataTable 組件的方式。

const tableColumns: HeaderColumn<any>[] = [
  {
    Header: 'sample text',
    accessor: (object) => object.title,
  },
  {
    Header: 'sample text',
    accessor: (object) => object.price,
  },
];
const tableData = [
    {
      title: 'title1',
      price: 'price1',
    },
    {
      title: 'title2',
      price: 'price2',
    },
    {
      title: 'title3',
      price: 'price3',
    },
  ];
<DataTable columns={tableColumns} data={tableData} />

控制台中的錯誤表明它在這一行的 DataTable 組件中(我不確定):

let tableColumns: HeaderColumn<any>[] = columns;

我在另一個項目中使用確切的組件並傳遞相同的數據,但沒有這樣的錯誤。 我在stackoverflow中搜索並發現了相同的問題,但無法解決問題。 有人可以在這方面幫助我嗎?
如果我的問題不完整或需要更多信息,請告訴我。

我找到了引發錯誤的代碼行,我可以解決問題。
當我使用 react-table 鈎子(useTable)時,在這一行中:

 const {
    getTableProps,
    headerGroups,
    rows,
    prepareRow,
    state: [{ selectedRows }],
  } = useTable({ columns: tableColumns, data }, useRowSelect);

我將數組更改為 object,問題就消失了。 這是最終代碼:

 const {
    getTableProps,
    headerGroups,
    rows,
    prepareRow,
    state: { selectedRows },
  } = useTable({ columns: tableColumns, data }, useRowSelect);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM