在玩笑测试中安装组件之前运行useEffect

时间:2019-05-31 21:18:33

标签: reactjs jestjs enzyme jsdom use-effect

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

我使用的是最新的玩笑,酶配置有adapter-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在渲染之后运行,但由于某种原因尚未挂载组件

0 个答案:

没有答案