React ref.current 在 useEffect 清理函数中为 null

React ref.current is null in useEffect cleanup function

我试图在清理期间(在组件卸载之前)访问引用。

像这样:

const Comp = () => {
    const imgRef = React.useRef();

    React.useEffect(() => {
      console.log('component mounted', imgRef); // During mount, imgRef.current is always defined
      return () => {
        console.log('component unmounting', imgRef); // imgRef.current always null here
      }
    }, []);  // also tried adding imgRef and imgRef.current still doesn't work in clean up

    return (
      <img src={'example.png'} ref={imgRef} />
    );

};
const App = () => {
  const [img, setImg] = React.useState(true);
  return <div>
    <button onClick={() => setImg(!img)}>toggle</button>
    {img && <Comp />}
  </div>;
};
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

即使在 useEffect 的依赖中添加 imgRef,imgRef.current 在 useEffect 的 return 中仍然为 null...

这适用于等效的 Class 组件,componentWillUnmount imgRef 已正确定义。

如何让它与钩子一起工作?

这很有帮助:

像这样的东西对我有用:

const imgRef = useRef();

useEffect(() => {
  let localRef = null;
  if (imgRef.current) localRef = imgRef.current;
  return () => {
     console.log('component unmounting', localRef); // localRef works here!
  }
}, []);

return (
  <img ref={imgRef} src="example.png" />
);