简体   繁体   English

ReactJS 在 function 内使用备忘录

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM