这是代码...
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height
};
}
let minNumberOfCards = Math.round(window.innerWidth / 120);
const [windowDimensions, setWindowDimensions] = React.useState(getWindowDimensions());
React.useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [windowDimensions,]);
我面临的问题是我需要计算要显示的卡片数量,并且得到的结果非常混乱:|。由于addEventListener是一个异步的东西。
我尝试的是minNumberOfCards = Math.round(windowDimensions.width/ 120);
再次buuuut,因为它是异步的,我设置的初始编号插入后不久后,我会得到正确的编号。基本上,我已将var minNumberOfCards设置为默认值9(例如)。
预期结果将是具有minNumberOfCards,具体取决于屏幕宽度。而已 !!!!!关于如何在不导致大量重新渲染的情况下实现此目标的任何想法/解决方案?
答案 0 :(得分:1)
import debounce from 'lodash.debounce';
const App = () => {
const [windowDimensions, setWindowDimensions] = useState('Change Window Size');
const [minNumberOfCards, setMinNumberOfCards] = useState(
Math.round(window.innerWidth / 120)
);
useEffect(() => {
// Better add a listener and only change the minNumberOfCards
},[...]);
useEffect(() => {
const handleResize = () => setWindowDimensions(getWindowDimensions());
const debouncedHandleResize = debounce(handleResize, 500);
window.addEventListener('resize', debouncedHandleResize);
return () => window.removeEventListener('resize', handleResize);
}, [windowDimensions]);
return (
<FlexBox>
<pre>{JSON.stringify(windowDimensions, null, 2)}</pre>
</FlexBox>
);
};
尝试在下一个沙箱中更改窗口大小: