1

我目前正在做一个小项目,涉及我使用带有外部包(react-tables)的反应备忘录。轻微的打嗝是一些用于表数据的数据是从 API 获取的,并且在第一次加载时会引发错误。纠正此错误的理想方法是什么?

//react tables docs sort of requires the data be memoized, I think.
const data = React.useMemo(
  () => [
    {
      col0: 1,
      col1: `${items[0].name} ${items[0].symbol}`, //items values are gotten from state
      col2: items[0].price,
      col3: `${items[0]['1d'].price_change_pct * 100}%`,
      col4: <ChartTable />,
    },
    {
      col0: 2,
      col1: `${items[1].name} ${items[1].symbol}`,
      col2: items[1].price,
      col3: `${items[1]['1d'].price_change_pct * 100}%`,
    },
    {
      col0: 3,
      col1: `${items[2].name} ${items[2].symbol}`,
      col2: items[2].price,
      col3: `${items[2]['1d'].price_change_pct * 100}%`,
    },
    {
      col0: 4,
      col1: `${items[3].name} ${items[3].symbol}`,
      col2: items[3].price,
      col3: `${items[3]['1d'].price_change_pct * 100}%`,
    },
  ],
  [],
);

const columns = React.useMemo(
  () => [
    { Header: '#', accessor: 'col0' },
    {
      Header: 'Name',
      accessor: 'col1', // accessor is the "key" in the data
    },
    {
      Header: 'Price',
      accessor: 'col2',
    },
    {
      Header: 'Change',
      accessor: 'col3',
    },
    {
      Header: 'Chart',
      accessor: 'col4',
    },
  ],
  [],
);

const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable({ columns, data });


//the code is table is then rendered

在第一次加载时,它会抛出一个错误,无法读取 undefined 的属性“名称”,这肯定是导致项目未定义的原因。但是,如果在呈现表之前定义了所述数据,则它可以正常工作。所以问题实际上是找到一种方法来延迟第一次渲染时数据函数的调用。

这个问题有可接受的解决方法吗?

PS:到目前为止,如果它们没有被记忆,它会从反应表代码本身引发内部错误,无法读取forEach未定义的属性

4

1 回答 1

2

这看似简单。

如果没有项目(例如),React.useMemo则应返回一个空数组。第二部分是*items的依赖项React.useMemo- 不要忘记将其添加到挂钩末尾的依赖项数组中:

  • 依赖意味着当它改变时,钩子应该重新运行。
//react tables docs sort of requires the data be memoized, I think.
const data = React.useMemo(
  () => !items.length ? [] : [
    {
      col0: 1,
      col1: `${items[0].name} ${items[0].symbol}`, //items values are gotten from state
      col2: items[0].price,
      col3: `${items[0]['1d'].price_change_pct * 100}%`,
      col4: <ChartTable />,
    },
    {
      col0: 2,
      col1: `${items[1].name} ${items[1].symbol}`,
      col2: items[1].price,
      col3: `${items[1]['1d'].price_change_pct * 100}%`,
    },
    {
      col0: 3,
      col1: `${items[2].name} ${items[2].symbol}`,
      col2: items[2].price,
      col3: `${items[2]['1d'].price_change_pct * 100}%`,
    },
    {
      col0: 4,
      col1: `${items[3].name} ${items[3].symbol}`,
      col2: items[3].price,
      col3: `${items[3]['1d'].price_change_pct * 100}%`,
    },
  ],
  [items],
);
于 2021-01-11T13:46:58.570 回答