useSize在乾坤微前端做了多tab的keepAlive时候 子应用的 DOM 节点可能已经被销毁或重新挂载,导致 ResizeObserver 监听的节点失效 直接白屏
- Dominant language
- TypeScript
- Stars
- 15k
- Forks
- 2.8k
- Avg merge
- 15h 7m
- Merged PRs (30d)
- 2
Description
## 报错信息:
TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
## 解决思路
```tsx
import { useState, useEffect } from 'react';
export const useSize = (domRef: React.RefObject) => {
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;
};
```
Contributor guide
Research direction
Locate the useSize hook implementation and first reproduce the reported failure when a kept-alive micro-frontend tab destroys or remounts its DOM node. Check the ResizeObserver callback and lifecycle handling, then verify that the hook no longer causes a blank screen when the referenced element is missing or disconnected.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- react, typescript
- Domain
- frontend
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100