首页 > 解决方案 > 在 React 中记忆一个函数

问题描述

有一个组件接收道具。

props 有一个数组的形状,对于这个数组的每个元素,一个函数将返回一个不同的组件来渲染。

function MainComponent ({ data }) => { // data is props, an array

  const specialFunction = (index) => {
    switch (index) {
    case 0:
      return <Component0 />;
    case 1:
      return <Component1 />;
    case 2:
      return <Component2 />;
    default:
      return null;
    }
  };
  ...
  return (
     ...
     data.map((item, index) => {
        ... // do other stuff with item
        <div>{specialFunction(index)}</div> // the function that we talk about
   
     ...
  );

如果道具不会改变,有没有办法记住这个结果?或者有什么更好的写法?

标签: javascriptreactjstypescriptreact-hooksreact-usememo

解决方案


带有空依赖数组的useCallback将是这里的最佳方法。useCallback 将返回回调的记忆版本,仅当其中一个依赖项发生更改时才会更改。由于我们的依赖数组是[],它只会被初始化一次,并且返回的 memonized 函数将在后续函数调用中使用。

const specialFunction = useCallback((index) => {
    switch (index) {
    case 0:
      return <Component0 />;
    case 1:
      return <Component1 />;
    case 2:
      return <Component2 />;
    default:
      return null;
    }
  }, []);

推荐阅读