React在更新DOM后运行效果(我们通常希望它以这种方式工作(。在您的情况下,效果在组件安装后运行,因此设置了
我希望这个useEffect
在第一次渲染时失败,因为我认为innerCarouselRef.current
在第一次呈现时是未定义的,它会调用getBoundingClientRect
。为什么它工作/为什么在useEffect
运行时定义innerCarouselRef.current
?
import React from 'react';
import { debounce } from 'lodash';
export default function Carousel({ RenderComponent }) {
const [innerCarouselWidth, setInnerCarouselWidth] = React.useState(0);
const [itemWidth, setItemWidth] = React.useState(0);
const innerCarouselRef = useRef();
const itemRef = useRef();
const content = data.map((el, i) => {
return (
<div key={`item-${i}`} ref={i === 0 ? itemRef : undefined}>
<RenderComponent {...el} />
</div>
);
});
useEffect(() => {
const getElementWidths = () => {
setInnerCarouselWidth(innerCarouselRef.current.getBoundingClientRect().width); // why doesn't this call to getBoundingClientRect() break?
setItemWidth(itemRef.current.getBoundingClientRect().width);
};
getElementWidths();
const debouncedListener = debounce(getElementWidths, 500);
window.addEventListener('resize', debouncedListener);
return () => window.removeEventListener('resize', debouncedListener);
}, []);
return (
<div className="inner-carousel" ref={innerCarouselRef}>
{content}
</div>
)
}
innerCarouselRef.current
。
我建议阅读useEffect
文档以获得更好的理解。