问题描述
我目前正在做一个小项目,该项目涉及我使用带有外部包(react-tables)的 react 备忘录。轻微的问题是用于表数据的一些数据是从 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
属性
解决方法
看似简单。
如果没有项目(例如),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],);