【发布时间】:2021-01-11 21:46:58
【问题描述】:
我目前正在做一个小项目,涉及我使用带有外部包(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
在第一次加载时,它会抛出一个错误,无法读取未定义的属性“名称”,这肯定是导致项目未定义的原因。但是,如果在呈现表之前定义了所述数据,则它可以正常工作。 所以问题实际上是想办法在第一次渲染时延迟 data 函数的调用。
对于这个问题是否有可接受的解决方法?
PS:到目前为止,如果它们没有被记忆,它会从反应表代码本身抛出一个内部错误无法读取属性forEach of undefined
【问题讨论】:
-
您能否发送更多代码来展示您如何初始化状态变量!?
-
它是一个从上下文中获取的空数组。该 api 非常广泛,因此我无法为每个单独的条目进行初始化。对于上下文:
const [items, setItems] = useState([]);
标签: javascript reactjs asynchronous async-await react-usememo