React Hooks - 将进程只传递一次道具的逻辑放在哪里?

React Hooks - where to put the logic that process passed props only once?

有时组件需要处理传递的 props 并保存在它的 state 中。由于处理过程可能很繁重,因此最好只完成一次。在挂钩之前,它通常在 constructorcomponentDidMount 中完成。

现在陷入困境,可以通过 useEffect 来实现,仅将 [] 作为第二个参数传递给 运行 一次,但我觉得这不是最好的地方 - 我们正在做的是处理道具并保存在状态中,这不是 副作用。来自文档:"Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects." 不要认为预处理属于这些。

那么用钩子做的最好的地方在哪里?

import React, {useMemo} from 'react';

const someExpensiveFunction = (a, b) => {
  // expensive stuff happens here
}

const someFunctionalComponent = ({ prop1, prop2 }) => {
  const someVariableDependentOnProps = useMemo(() => someExpensiveFunction(prop1, prop2), [prop1, prop2]);
  return <div>{someVariableDependentOnProps}</div>
}

根据文档:

useMemo will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.

https://reactjs.org/docs/hooks-reference.html#usememo