触发useState

时间:2020-01-15 08:15:18

标签: javascript reactjs react-hooks

我有一个组件,并使用不同的道具有条件地渲染它。

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

该组件具有useState(false)useEffect钩子。 useEffect确定屏幕位置何时到达dom元素,并触发useStatetrueelementPosition < screenPosition。然后我的state触发dom元素上的类: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>
  );
};

问题:它适用于我的第一个渲染。但是当我使用不同的道具切换组件时,我的state最初是true,但是我没有动画。

我注意到,如果我有两个组件(ComponentA, ComponentB)而不是一个(ComponentA),则可以正常工作。

1 个答案:

答案 0 :(得分:0)

当您的组件不在这样的视图中时,尝试将isViewed设置为false:

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

您可以这样做:

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

加上无需多次渲染相同的组件,您只能更改道具:

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