React Functional Component - 在哪里存储从道具计算的转换值

React Functional Component - Where to store transformed value calculated from props

假设我有以下重计算函数:

function heavyCalculator(str:string):string{
  //Do some heavy calculation
  return result;
}
function SomeComponent({prop1,prop2,prop3,prop4}:Props){
  useEffect(()=>{
    const result = heavyCalculator(prop3);
    //How should i store the result?
  },[prop3])
  return <span>{resultFromHeavyCalculation}</span>;
}

我应该如何以一种不会在每次渲染/道具更改时都重新计算的方式存储计算结果?

我应该使用“useMemo”还是使用“useState”并仅在更改prop3时将其设置在“useEffect”中?

这基本上是 useMemo 的主要用例。尽管如果将结果存储在 useState 变量中,使用 useEffect(() => ..., [prop3]) 的方法也可以工作,但 useMemo 需要更少的样板文件:

function SomeComponent({prop1,prop2,prop3,prop4}:Props){
  const resultFromheavyCalculation = useMemo(() => heavyCalculator(prop3), [prop3])
  return <span>{resultFromHeavyCalculation}</span>;
}

您可以了解有关 useMemo in the official documentation 的更多信息。那里的示例实际上与您提供的示例非常相似。

如果你真的下定决心不惜一切代价避免 useMemo,答案将是:

    function SomeComponent({prop1,prop2,prop3,prop4}:Props){
      const [resultFromHeavyCalculation, setResultFromHeavyCalculation] = useState();
      useEffect(()=>{
          const result = heavyCalculator(prop3);
          setResultFromHeavyCalculation(result);
      },[prop3]), [prop3])
      return <span>{resultFromHeavyCalculation}</span>;
    }