首页 > 解决方案 > 在开玩笑测试中安装组件之前运行的 useEffect

问题描述

useEffect 似乎在安装组件之前运行,当我对渲染中的元素执行 document.getElementsByClassName 时,它​​是未定义的。它不是有条件地渲染或任何东西。

我正在使用最新的笑话,酶配置了适配器 16。有谁知道发生了什么?

从我所看到的正确配置它,没有错误


const IndustriesGraphic = () => {
  const canvas = useRef(null);

  useEffect(() => {
    const { clientWidth, clientHeight } = document.getElementsByClassName('industries-graphic__canvas-container')[0];

    canvas.current.style.width = `${clientWidth}px`;
    canvas.current.style.height = `${clientHeight}px`;

    const scale = clientWidth < clientHeight ? clientWidth : clientHeight;
    createGraphic(scale);

    const resizeGraphic = () => {
      const canvasContainer = document.getElementsByClassName('industries-graphic__canvas-container')[0];

      if (!canvasContainer) {
        return;
      }

      const { clientWidth: newWidth, clientHeight: newHeight } = canvasContainer;
      canvas.current.style.width = `${newWidth}px`;
      canvas.current.style.height = `${newHeight}px`;
      const newScale = newWidth < newHeight ? newWidth : newHeight;
      createGraphic(newScale);
    };

    window.addEventListener('resize', resizeGraphic);

    return window.removeEventListener.bind(null, 'resize', resizeGraphic);
  }, []);

  return (
    <div className="industries-graphic">
      <h1 className="industries-graphic__header">{industriesConfig.header}</h1>
      <div className="industries-graphic__canvas-container">
        <canvas ref={canvas} id={CANVAS_ID} />
      </div>
      <div className="industries-graphic__tablet-graphic">
        <span className="industries-graphic__tablet-icon">
          <img src={cryptoIcon} alt="crypto" />
        </span>
        <span className="industries-graphic__tablet-icon">
          <img src={securityIcon} alt="crypto" />
        </span>
        <span className="industries-graphic__tablet-icon">
          <img src={financialIcon} alt="crypto" />
        </span>
        <span className="industries-graphic__tablet-icon">
          <img src={entertainmentIcon} alt="crypto" />
        </span>
        <span className="industries-graphic__tablet-icon">
          <img src={socialIcon} alt="crypto" />
        </span>
        <span className="industries-graphic__tablet-icon">
          <img src={medicalIcon} alt="crypto" />
        </span>
      </div>
      <div className="industries-graphic__scroll-text">SCROLL TO CONTINUE</div>
    </div>
  );
};


我希望 useEffect 在渲染后运行,但由于某种原因该组件尚未安装

标签: reactjsjestjsenzymejsdomuse-effect

解决方案


推荐阅读