开发者问题收集

修复未捕获的类型错误:无法读取未定义的属性(读取“style”)

2022-05-15
3482

I'm trying to make a slideshow in my react app. I'm using the below function for the slideshow.

var myIndex = 0;
carousel();

function carousel() {
  var i;
  var x = document.getElementsByClassName("diabetes-day");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  myIndex++;
  if (myIndex > x.length) {
    myIndex = 1
  }
  x[myIndex - 1].style.display = "block";
  setTimeout(carousel, 5000); // Change image every 5 seconds
}
<div className="slideshow-container">
  <div className="diabetes-news">
    <img className="diabetes-day" src={DiabetesDay}/>
    <img className="diabetes-day" src={Symptoms}/>
    <img className="diabetes-day" src={Managing}/>
  </div>
</div>

When I run the code the slideshow works. But as soon as I refresh the page all the contents in the page disappears and I get the following error in my console. Screenshot of the Error

I'm not quite sure why it stops working once the page is refreshed. It would be great if someone could guide me on how to fix this.

2个回答

我也遇到了刷新页面时出现相同错误的情况。我使用了 useEffect 钩子来解决此错误。

useEffect(() => {
  //your code
}, [value that is changing]);
Krishna Nand Dubey
2022-06-04

看来你正在使用 reactjs,最好用这个来更改你的代码:

const {useState, useEffect} = React;

const Example = () => {
  const [imageIndex, setImageIndex] = useState(0);

  // change these images with yours
  const imagesSrc = [
    "https://cdn.pixabay.com/photo/2022/03/03/11/19/nature-7045133_960_720.jpg",
    "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg",
    "https://cdn.pixabay.com/photo/2013/07/18/20/26/sea-164989_960_720.jpg",
  ];

  const carousel = () => {
    setImageIndex((prev) => (prev < 2 ? prev + 1 : 0));
  };

  useEffect(() => {
    const timer = setInterval(() => {
      carousel();
    }, 2000); // set the which timer you want
    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <div className="slideshow-container">
      <div className="diabetes-news">
        <img className="diabetes-day" src={imagesSrc[imageIndex]} alt="" />
      </div>
    </div>
  );
};

// Render it
ReactDOM.render(
  <Example/>,
  document.getElementById("react")
);
.diabetes-day{
  width: 200px;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
ismail bilal
2022-05-15