反应自定义钩子和useMemo钩子

时间:2020-07-06 20:18:28

标签: reactjs react-hooks react-usememo

我想在我的react应用程序中记住两个“昂贵”的函数,因为它们需要很长时间才能呈现。昂贵的函数用于数组映射。我想记住数组映射的每个结果,以便如果更改数组的一个元素,则仅重新计算该元素的昂贵函数。 (而且要独立地记住昂贵的函数,因为有时只需要重新计算一个即可。)我在如何记住和传递当前数组值方面感到困惑。

这是工作示例,没有备注:

import React, { useMemo, useState } from "react";

const input = ["apple", "banana", "cherry", "durian", "elderberry", "apple"];

export default function App() {
  const output = input.map((msg, key) => createItem(msg, key));
  return <div className="App">{output}</div>;
}

const createItem = (message, key) => {   // expensive function 1
  console.log("in createItem:", key, message);

  return (
    <div key={key}>
      <strong>{"Message " + (1 + key)}: </strong>
      {message} =>{" "}
      <span
        id={"preview-" + key}
        dangerouslySetInnerHTML={{ __html: msgSub(message) }}
      />
    </div>
  );
};

const msgSub = message => {   // expensive function 2
  const messageSub = message.replace(/[a]/g, "A").replace(/[e]/g, "E");
  console.log("in msgSub:", message, messageSub);
  return messageSub;
};

(我没有在SO的编辑器上运行它,因此请在codesandbox上查看并运行它。)

这里one of my attempts使用自定义钩子和useMemo钩子。

任何指导将不胜感激!

还有用于说明如何在SO的编辑器中工作的奖励积分!

2 个答案:

答案 0 :(得分:1)

我的第一步是更改createItem,以使Item是其唯一的功能组件。这意味着我可以记住<Item/>组件,以便仅在props更改时才渲染,而重要的是消息和键/索引(就像您之前渲染值一样)。

https://codesandbox.io/s/funny-chaplygin-pvfoj的工作示例。

const Item = React.memo(({ message, index }) => {
  console.log("Rendering:", index, message);

  const calculatedMessage = msgSub(message);

  return (
    <div>
      <strong>{"Message " + (1 + index)}: </strong>
      {message} =>{" "}
      <span
        id={"preview-" + index}
        dangerouslySetInnerHTML={{ __html: calculatedMessage }}
      />
    </div>
  );
});

const msgSub = message => {
  // expensive function 2
  const messageSub = message.replace(/[a]/g, "A").replace(/[e]/g, "E");
  console.log("in msgSub:", message, messageSub);
  return messageSub;
};

您可以看到,在初始渲染时,它会用其message渲染所有项目,尤其是apple渲染两次。

如果两个组件彼此独立地渲染,并且碰巧使用相同的道具,则将渲染这两个组件。 React.memo不会保存组件渲染。

它必须两次渲染Item组件<Item message="apple" />,一次在索引0代表apple,在索引5 apple再次呈现。


您会注意到我在应用程序中放置了一个按钮,单击该按钮将更改数组的内容。

稍微改变一下原始数组,我将carrot放在原始数组的索引4中,并在更新时将其移到新数组的索引2中。

  const [stringArray, setStringArray] = React.useState([
    "apple",
    "banana",
    "cherry",
    "durian",
    "carrot",
    "apple" // duplicate Apple
  ]);

  const changeArray = () =>
    setStringArray([
      "apple",
      "banana",
      "carrot",  // durian removed, carrot moved from index 4 to index 2
      "dates", // new item
      "elderberry", // new item
      "apple"
    ]);

如果您查看控制台,您会看到在第一个渲染器上看到的是in msgSub: carrot cArrot,但是当我们更新数组时,会再次调用in msgSub: carrot cArrot。这是因为<Item />上的密钥因此被强制重新呈现。这是正确的,因为我们的密钥是基于索引的,并且胡萝卜更改了位置。但是,您说msgSub是一个昂贵的函数...


本地记忆化

我在您的数组中发现您有两次apple

const input = [“苹果”,“香蕉”,“樱桃”,“榴莲”,“接骨木”,“苹果”];

我认为您想记住此计算,以便如果先前计算过apple时就不再计算apple

我们可以将计算出的值存储在我们自己的备忘录状态中,这样我们就可以查找消息值,并查看我们以前是否已计算出它。

const [localMemoization, setLocalMemoization] = useState({});

我们要确保在stringArray更改时更新此localMemoization。

  React.useEffect(() => {
    setLocalMemoization(prevState =>
      stringArray.reduce((store, value) => {
        const calculateValue =
          prevState[value] ?? store[value] ?? msgSub(value);
        return store[value] ? store : { ...store, [value]: calculateValue };
      })
    );
  }, [stringArray]);

此行const calculateValue = prevState[value] ?? store[value] ?? msgSub(value);

  • 检查先前的状态以查看其是否具有先前的值(对于胡萝卜将第一个数组移动到第二个数组的情况)。
  • 检查当前商店是否具有该值(对于第二个Apple案例)。
  • 最后,如果什么都没看到,我们将使用昂贵的函数来首次计算该值。

使用与先前渲染相同的逻辑,我们现在查找计算出的值并将其传递到<Item>中,以便它是React.memo可以防止在App再次渲染时重新渲染该组件。

const output = stringArray.map((msg, key) => {
    const expensiveMessage = localMemoization[msg];
    return (
      <Item
        key={key}
        message={msg}
        calculatedValue={expensiveMessage}
        index={key}
      />
    );
  });

这里的工作示例https://codesandbox.io/s/attempt-with-custom-hooks-and-usememo-y3lm5?file=/src/App.js:759-1007

由此,在控制台中,我们可以看到在第一个渲染中,apple仅计算了一次。

当数组更改时,我们不再计算carrot,而仅计算更改后的项目dateselderberry

答案 1 :(得分:0)

使项目成为纯组件:

const id = ((id) => () => id++)(1); //IIFE creating id
//pure component
const Item = React.memo(function Item({ increase, item }) {
  console.log('rendering id:', item.id);
  return (
    <ul>
      <button onClick={() => increase(item.id)}>
        {item.count}
      </button>
    </ul>
  );
});
const App = () => {
  const [items, setItems] = React.useState([]);
  //use callback, increase only created on app mount
  const increase = React.useCallback(
    (id) =>
      setItems((items) =>
        //use state setter callback
        //no dependencies for useCallback and no stale
        //closures
        items.map((item) =>
          item.id === id
            ? { ...item, count: item.count + 1 }
            : item
        )
      ),
    [] //no dependencies
  );
  return (
    <div>
      <div>
        <button
          onClick={() =>
            setItems((items) => [
              { id: id(), count: 0 },
              ...items,
            ])
          }
        >
          add counter
        </button>
      </div>
      <ul>
        {items.map((item) => (
          <Item
            key={item.id}
            item={item}
            increase={increase}
          />
        ))}
      </ul>
    </div>
  );
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>