React窗口缩放后卡顿:实现react-simple-image-slider响应式
解决react-simple-image-slider响应式适配时的窗口resize卡顿问题
你的代码在窗口resize时出现卡顿,核心问题在于:
useLayoutEffect未设置依赖数组,也未清理resize监听器,导致组件每次渲染都会重复绑定新的监听器,窗口变化时触发大量重复状态更新- resize事件本身触发频率极高,每次窗口像素变动就触发更新,加剧了组件重渲染的频率
解决方案
- 添加监听器清理逻辑:避免内存泄漏和重复绑定
- 给resize事件加防抖:限制状态更新频率,减少不必要的重渲染
- 优化状态更新条件:仅当宽度实际变化时才更新状态
修改后的完整代码
import './App.css'; import { useLayoutEffect, useState } from 'react'; import SimpleImageSlider from 'react-simple-image-slider'; // 防抖函数,延迟执行回调,默认200毫秒 const debounce = (func, delay = 200) => { let timeoutId; return (...args) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => func.apply(this, args), delay); }; }; function App() { const [widthAndHeight, setWidthAndHeight] = useState([window.innerWidth, 600]); useLayoutEffect(() => { // 防抖后的尺寸更新函数 const updateDimensions = debounce(() => { const newWidth = window.innerWidth; // 仅当宽度发生变化时才更新状态 if (newWidth !== widthAndHeight[0]) { // 可根据窗口宽度动态设置高度,适配移动端 const newHeight = newWidth < 768 ? 300 : 600; setWidthAndHeight([newWidth, newHeight]); } }); window.addEventListener('resize', updateDimensions); // 组件卸载时移除监听器 return () => { window.removeEventListener('resize', updateDimensions); }; }, [widthAndHeight]); const images = [ { url: "logos/ethiopia.png" }, { url: "logos/favicon.ico" }, { url: "logos/gear.png" }, { url: "logos/gear.jpg" } ]; return ( <div> <SimpleImageSlider style={{ margin: '0 auto', marginTop: '0px'}} className="slider" width={widthAndHeight[0]} height={widthAndHeight[1]} slideDuration={0.5} // 建议使用合理的过渡时长,默认0.5秒 loop={true} autoPlay={true} images={images} showBullets={false} showNavs={true} /> </div> ); } export default App;
额外优化建议
- 防抖延迟时间可根据需求调整(200-300毫秒),平衡响应速度和性能
- 检查图片资源大小,过大的图片会加重resize时的渲染负担,建议提前压缩处理
内容的提问来源于stack exchange,提问作者gsharew
相关产品推荐
相关产品推荐

