我正在尝试使用本指南实现一个反应表:
https://github.com/tannerlinsley/react-table/blob/master/docs/quickstart.md
在指南中的某一点,它说使用 React.useMemo 创建数据:
const columns = React.useMemo(
() => [
{
Header: 'Column 1',
accessor: 'col1', // accessor is the "key" in the data
},
{
Header: 'Column 2',
accessor: 'col2',
},
],
[]
)
当我这样做时,我将这一行复制并粘贴到我的代码中(用我自己的数据替换数据):
class Blog extends Component {
...
createTable() {
const cols = React.useMemo(
// copy and paste here
);
// more table creation code
return (
// jsx for table
);
}
...
}
但是当我运行它时,它告诉我:
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
所以在谷歌搜索这个问题之后,我收集到我需要在 React 函数中调用 useMemo 。所以我创建了这个:
import React from 'react';
const getCols = () => {
return React.useMemo(() => [
{
Header: 'title',
accessor: 'titleCol'
},
{
Header: 'body',
accessor: 'bodyCol'
},
{
Header: 'last updated',
accessor: 'updatedAtCol'
}
], []);
};
export default getCols;
在我的博客课上:
class Blog extends Component {
...
createTable() {
const cols = getCols();
// more table creation code
return (
// jsx for table
);
}
...
}
但现在它告诉我:
React Hook "React.useMemo" is called in function "getCols" which is neither a React function component or a custom React Hook function
为什么它不是 React 函数?
更重要的是,调用 useMemo(...) 的正确方法是什么?
谢谢。