简体   繁体   English

React 的错误:组件在页面刷新之前不会呈现

[英]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.如果我有 Box 组件并切换到 Carousel 组件,它在我刷新页面之前不起作用,但是如果我先渲染 Carousel 组件,渲染 Box 然后 go 回到 Carousel 它可以工作。 Is this a bug with ReactDOM or what?这是 ReactDOM 的错误还是什么?

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.我需要在组件被调用时重新渲染它,以便它正常工作,即使我直接在我的页面上调用 AliceCarousel 组件我仍然有这个问题。

Is this something to do with React or the component itself?这与 React 或组件本身有关吗? Thanks谢谢

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.您的useEffect逻辑导致无限循环,因为在将 state 更改为true后,通过将 state 放在 dep 数组[carousel]中,您将其从清理 ZC1C425268E683849F1AB45A 更改回false

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

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

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