在自定义钩子中,为什么在useEffect之前发生返回

时间:2020-04-22 10:40:35

标签: javascript reactjs react-hooks

考虑这个常见的著名钩子

// Copied from https://usehooks.com/usePrevious/
// License is Unlicensed, https://github.com/gragland/usehooks/blob/master/LICENSE
function usePrevious<T>(value: T): T | undefined {
  // The ref object is a generic container whose current property is mutable ...
  // ... and can hold any value, similar to an instance property on a class
  const ref = React.useRef<T>();

  // Store current value in ref
  React.useEffect(() => {
    ref.current = value;
  }, [value]); // Only re-run if value changes

  // Return previous value (happens before update in useEffect above)
  return ref.current;
}

为什么我们要确保返回值上方的useEffect在返回引用并因此为我们提供旧值之后运行?

0 个答案:

没有答案