Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useSize在乾坤微前端做了多tab的keepAlive时候 子应用的 DOM 节点可能已经被销毁或重新挂载,导致 ResizeObserver 监听的节点失效 直接白屏 #2699

Open
ngwszsd opened this issue Dec 13, 2024 · 0 comments

Comments

@ngwszsd
Copy link

ngwszsd commented Dec 13, 2024

报错信息:

TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

解决思路

import { useState, useEffect } from 'react';

export const useSize = (domRef: React.RefObject<HTMLElement>) => {
  const [size, setSize] = useState({ width: 0, height: 0 });

  useEffect(() => {
    const element = domRef.current;

    if (!element) {
      console.warn('`useSize`: domRef is null or undefined.');
      return;
    }

    if (typeof ResizeObserver === 'undefined') {
      console.warn('`useSize`: ResizeObserver is not supported by this browser.');
      return;
    }

    let isMounted = true; // 防止卸载后更新状态
    const observer = new ResizeObserver(entries => {
      if (!isMounted) return;

      try {
        const entry = entries[0];
        if (entry && entry.target.isConnected) {
          const { width, height } = entry.contentRect;
          setSize({ width, height });
        }
      } catch (error) {
        console.error('`useSize`: Error in ResizeObserver callback.', error);
      }
    });

    observer.observe(element);

    return () => {
      isMounted = false;
      observer.disconnect(); // 确保在卸载时断开监听
    };
  }, [domRef]);

  return size;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant