ocl*_*yke 7 javascript performance events typescript reactjs
应用程序需要窗口的内部大小。React 模式建议在一次性效果挂钩中注册一个事件侦听器。调用window.addEventListener似乎只发生一次,但事件侦听器堆积如山,对性能产生负面影响。
这是重现此问题的精简源代码
import React, {useState, useEffect} from 'react';
const getWindowRect = () => {
return new DOMRect(0, 0, window.innerWidth, window.innerHeight);
}
// custom hook to track the window dimensions
const useWindowRect = () => {
// use state for the aspect ratio
let [rect, setRect] = useState(getWindowRect);
// useEffect w/o deps should only be called once
useEffect(() => {
const resizeHandler = () => { setRect(getWindowRect()); };
window.addEventListener('resize', resizeHandler);
console.log('added resize listener');
// return the cleanup function
return () => {
window.removeEventListener('resize', resizeHandler);
console.log('removed resize listener');
}
}, []);
// return the up-to-date window rect
return rect;
}
const App = () => {
const window_rect = useWindowRect();
return <div>
{window_rect.width/window_rect.height}
</div>
};
export default App;
Run Code Online (Sandbox Code Playgroud)
相关的控制台输出显示:
added resize listener
Run Code Online (Sandbox Code Playgroud)
这是预期的结果,监听器只添加一次,无论应用程序重新渲染多少
参考,窗口未调整大小最大侦听器:56

调整性能,window.addEventListener注释掉最大听众数:49

假设在 JSFiddle 或 CodePen 上运行性能指标会很困难,我在这个 repo 上提供了一个完整的演示:oclyke-exploration/resize-handler-performance只要你安装了 node 和 yarn,你就可以轻松运行演示。
window.removeEventListener相同window.addEventListener- 尽管当效果只发生一次时,这甚至不应该发挥作用create-react-app使用 react-scripts 4.0.0在新项目上重现了这个问题有没有人对这个问题有解释?我难住了!(相关:其他人可以重现这个问题吗?)
| 归档时间: |
|
| 查看次数: |
87 次 |
| 最近记录: |