threejs-tutorial icon indicating copy to clipboard operation
threejs-tutorial copied to clipboard

关于示例代码中的小问题

Open hellochenk opened this issue 4 years ago • 2 comments

大部分示例代码当中都会有诸如

useEffect(() => {
   // ...
}, [someRef])

<canvas ref={someRef}>

的代码

但实际上ref作为effect的dep并不安全。

官方建议使用

function MeasureExample() {
  const [height, setHeight] = useState(0);

  const measuredRef = useCallback(node => {
    if (node !== null) {
      setHeight(node.getBoundingClientRect().height);
    }
  }, []);

  return (
    <>
      <h1 ref={measuredRef}>Hello, world</h1>
      <h2>The above header is {Math.round(height)}px tall</h2>
    </>
  );
}

原文链接 is-it-safe-to-use-ref-current-as-useeffects-dependency-when-ref-points-to-a-dom 官网解释

并再次感谢你的教程

hellochenk avatar Jun 14 '22 03:06 hellochenk

“ref作为effect的dep并不安全” 这句话中的 “不安全” 应该是指 useEffect 中在某些情况下可能存在闭包陷阱吧。 不过对于我写的示例中,是不存在这个问题的。

你提到的改用 useCallback 我认为只是 用另外一个 hook 来解决这个 hook 可能存在的问题。 作为讲解 Three.js 的示例代码,用过多 hook 只会让示例显得更加复杂。

如果你很介意我那种写法,可以不使用 useRef,而是在 useEffect 中直接通过原生 document.querySelector('canvas') 这种方式获取到 canvas DOM 元素。

puxiao avatar Jun 14 '22 06:06 puxiao

  1. 是的,我想表达的就是闭包陷阱
  2. 确实如此,示例代码运行正常,但我没搞懂这是为什么。
  3. 因为发现将ref作为effect的dep时,会有代码运行不正常的情况。然后在搜索问题时想到这里的示例代码可能也存在同样问题。不过作为示例代码,我赞同专注核心点 threejs。
  4. 非杠,我只是想让代码更好点~

hellochenk avatar Jun 14 '22 11:06 hellochenk