[英]ReactJS useMemo inside function
I have this function:我有这个 function:
const handleSearch = (event) => {
const currentValue = event?.target?.value;
const filteredData = searchTable(currentValue, originalData);
setDataToTable(filteredData);
};
I tried to use useMemo()
to memoize the value of filteredData
in order to not perform the function searchTable
because it's slow.我尝试使用
useMemo()
来记住filteredData
数据的值,以便不执行searchTable
搜索表,因为它很慢。 I tried this inside the handleSearch
function:我在
handleSearch
function里面试过这个:
const filteredData = useMemo(() => searchTable(currentValue, originalData), [currentValue]);
But I get the Hooks can only be called inside of the body of a function component
message which is correct.但是我得到
Hooks can only be called inside of the body of a function component
这是正确的。
How should I use useMemo
for my case?我应该如何在我的案例中使用
useMemo
?
You must store the search query into a state variable
and use useMemo
with this variable to compute the filtered data.您必须将搜索查询存储到
state variable
中,并将useMemo
与此变量一起使用来计算过滤后的数据。
function App() {
const [query, setQuery] = useState();
const filteredData = useMemo(() => searchTable(query, originalData), [query]);
function handleSearch(event) {
setQuery(event?.target?.value);
}
return (...)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.