简体   繁体   中英

Triggering useState

I have a component and render it conditionally with different props.

      {activeNavItem === 'Concept Art' ? (
        <Gallary
          images={conceptArtImages}
          sectionRef={sectionRef}
        />
      ) : (
        <Gallary
          images={mattePaintingImages}
          sectionRef={sectionRef}
        />
      )}

This component has useState(false) and useEffect hooks. useEffect determines when screen position reaches the dom element and it triggers useState to true : elementPosition < screenPosition . Then my state triggers class on dom element: state ? 'animationClass' : '' state ? 'animationClass' : '' .

const Gallary = ({ images, sectionRef }) => {
  const [isViewed, setIsViewed] = useState(false);

  useEffect(() => {
    const section = sectionRef.current;

    const onScroll = () => {
      const screenPosition = window.innerHeight / 2;
      const sectionPosition = section.getBoundingClientRect().top;
      console.log(screenPosition);

      if (sectionPosition < screenPosition) setIsViewed(true);
    };

    onScroll();
    window.addEventListener('scroll', onScroll);

    return () => {
      window.removeEventListener('scroll', onScroll);
    };
  }, [sectionRef]);

  return (
    <ul className="section-gallary__list">
      {images.map((art, index) => (
        <li
          key={index}
          className={`section-gallary__item ${isViewed ? 'animation--view' : ''}`}>
          <img className="section-gallary__img" src={art} alt="concept art" />
        </li>
      ))}
    </ul>
  );
};

Problem: it works on my first render. But when I toggle component with different props, my state iniatially is true and I haven't animation.

I notice that if I have two components( ComponentA, ComponentB ) instead of one( ComponentA ) it works fine.

try setting isViewed to false when your component is not in view like this:

if (sectionPosition < screenPosition && !isViewed){
setIsViewed(true);
}
else{
if(isViewed) 
   setIsViewed(false);
}

and you can do it like this:

if (sectionPosition < screenPosition && !isViewed){
setIsViewed(state=>!state);
}
else{
if(isViewed) 
   setIsViewed(state=>!state);
}

plus no need to render same component multiple times, you can change props only:

  <Gallary
      images={activeNavItem === 'ConceptArt'?conceptArtImages:mattePaintingImages}
      sectionRef={sectionRef}
    />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM