Answer the question
In order to leave comments, you need to log in
Why is the hook called 2 times?
function MainPage() {
let slider = React.createRef();
let slideSpeed = 500;
let [slidesCount, setSlidesCount] = useState(0);
let [leftDragger, setLeftDragger] = useState(0);
let [activeSlide, setActiveSlide] = useState(0);
//Хук вызывается 2 раза
useEffect(() => {
setSlidesCount(document.querySelectorAll('.slick-list .slick-slide:not(.slick-cloned)').length)
console.log(slidesCount) //Сначала выводит 0, потом 4
}, [slidesCount]);
let settings = {
dots: false,
infinite: true,
speed: slideSpeed,
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
beforeChange: (currentSlide, nextSlide) => {
setActiveSlide(nextSlide);
console.log(leftDragger);
if(activeSlide == 0) {
setLeftDragger(100 / slidesCount * (activeSlide + 1) / 2 + "%");
} else {
setLeftDragger(20)
}
}
};
return(
<div className="main-page">
<section className="about">
<Slider ref={slider} {...settings}>
</Slider>
<SliderNav slideSpeed={slideSpeed} sliderDOM={slider} />
</section>
<section className="remembers">
</section>
</div>
)
}
export default MainPage;
Answer the question
In order to leave comments, you need to log in
because you initialize it with 0
then you subscribe to slidesCount and the hook is called with 0
let [slidesCount, setSlidesCount] = useState(0);
useEffect(() => {
setSlidesCount(document.querySelectorAll('.slick-list .slick-slide:not(.slick-cloned)').length)
console.log(slidesCount) //Сначала выводит 0, потом 4
}, [slidesCount]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question