简体   繁体   English

触发 useState

[英]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.这个组件有useState(false)useEffect钩子。 useEffect determines when screen position reaches the dom element and it triggers useState to true : elementPosition < screenPosition . useEffect确定屏幕位置何时到达 dom 元素并触发useStatetrueelementPosition < screenPosition Then my state triggers class on dom element: state ? 'animationClass' : ''然后我的state在 dom 元素上触发类: state ? 'animationClass' : '' 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.但是当我用不同的道具切换组件时,我的state最初是true ,我没有动画。

I notice that if I have two components( ComponentA, ComponentB ) instead of one( ComponentA ) it works fine.我注意到如果我有两个组件( ComponentA, ComponentB )而不是一个( ComponentA )它工作正常。

try setting isViewed to false when your component is not in view like this:当您的组件不在视图中时,请尝试将isViewed设置为 false:

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}
    />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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