Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

javascript - Bug with React: component not rendering until page is refreshed

I have this carousel component that I'm calling from a page but it's not showing until I refresh the page. If I have the Box component and switch to the Carousel component it doesn't work until I refresh the page but if I render the Carousel component first, render Box then go back to Carousel it works. Is this a bug with ReactDOM or what?

My carousel component:

const Carousel = () => {
  const { carousel, setCarousel } = useContext(AppContext);

  useEffect(() => {
    setCarousel(true);
    return () => {
      setCarousel(false);
    };
  }, [carousel]);

  const items = ["image1.svg", "image2.svg", "image1.svg", "image2.svg"];

  const responsive = {
    0: { items: 1 },
    1024: { items: 2 },
  };

  return (
    <div
      className={`container flex`}
      style={{
        marginTop: "40px",
      }}>
      <AliceCarousel
        disableDotsControls
        disableButtonsControls
        autoHeight={true}
        autoWidth={true}
        responsive={responsive}
        animationType='slide'>
        {items.map((i, index) => (
          <img src={i} key={index} alt='' srcSet='' className={Styles.slider} />
        ))}
      </AliceCarousel>
         </div>
  );
};

And I'm switching/calling it on another component like this:

const { carousel, modalIsOpen, openModal, closeModal } = useContext(
  AppContext
);

return (
  <div className={carousel ? Styles.layout : ""}>
    <div>
      <Box />
    </div>
  </div>
)

I need to make the component re-render when it's called or something so that it works properly, even when I call the AliceCarousel component on my page directly I still have this issue.

Is this something to do with React or the component itself? Thanks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your useEffect logic leads to infinity loop as after changing the state to true, by having the state in dep array [carousel], you changing it back to false from the cleanup function.

// Useless useEffect, always false.
useEffect(() => {
    setCarousel(true);
    return () => {
      setCarousel(false);
    };
}, [carousel]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...