【问题标题】:Memoize a function in React在 React 中记忆一个函数
【发布时间】:2021-12-23 22:23:22
【问题描述】:

有一个组件接收道具。

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
   
     ...
  );

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

【问题讨论】:

  • 你有没有尝试明显的 - useMemo(specialFunction, [index])
  • 你可以试试useMemomemo
  • 对于函数,也可以使用useCallback。
  • 在您的示例中,该函数可能位于 MainComponent 之外。

标签: javascript reactjs typescript react-hooks react-usememo


【解决方案1】:

有几种方法可以实现这一点:

  1. 您可以使用状态来存储数组

const [components] = useState([&lt;Component0 /&gt;, &lt;Component1 /&gt;, &lt;Component2 /&gt;])

然后在尝试渲染时使用components[index]

  1. 您可以尝试useCallback 来记忆您的功能。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 每次渲染调用都会执行 n 次(其中 n 是 data 的长度)。 “它只会执行一次”具有误导性
    【解决方案3】:

    其他模式,我认为在这种情况下最优雅的是使用:

    const components = {
       0: <Component0 />,
       1: <Component1 />,
       2: <Component2 />,
    }
    
    /*
    or
    const components = [<Component0 />, <Component1 />, <Component2 />]
    */
    
    function MainComponent ({ data }) => {
      ...
      return (
         ...
         data.map((item, index) => 
            <div>{components[index] || null}</div>
         ...
      );
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-02
      • 2020-04-07
      • 2015-09-05
      • 2021-10-23
      • 1970-01-01
      • 2014-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多