将图像SRC与来自阵列的图像在React的间隔上进行

发布于 2025-02-06 07:13:00 字数 694 浏览 1 评论 0原文

这应该很简单,但是从结果中我一直保持怪异的行为。

基本上,我有一系列图像:

  const images = [img1, img2, img3, img4, img5, img6];

我也有一个图像索引:

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

然后我对索引进行一些增量:

const switchImage = () => {
if (imageIndex === images.length - 1) {
  setImageIndex(0);
} else {
  setImageIndex(imageIndex + 1);
}
return imageIndex;
}

然后我从使用效率上调用此函数:

  useEffect(() => {
setInterval(() => {
  switchImage();
}, 1000);
 }, []);

最后我添加了html:

<img src={images[imageIndex]} />

结果通常是粘在上面第二张图像并停止增加,所以我认为问题可能与使用效率以及组件渲染的方式有关。

This should be fairly simple, but I keep getting a weird behaviour from the result.

Basically, I have an array of images:

  const images = [img1, img2, img3, img4, img5, img6];

I also have an image index:

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

Then I do a little incrementation of the index:

const switchImage = () => {
if (imageIndex === images.length - 1) {
  setImageIndex(0);
} else {
  setImageIndex(imageIndex + 1);
}
return imageIndex;
}

Then I call this function from a useEffect:

  useEffect(() => {
setInterval(() => {
  switchImage();
}, 1000);
 }, []);

And finally I add the html:

<img src={images[imageIndex]} />

The result is usually it gets stuck on the second image and stops incrementing, so I thought the issue might be with the useEffect and the way the component is rendering.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怎言笑 2025-02-13 07:13:00

您需要使用usestate设置器函数的第二种方法签名,该函数为您提供了上一个状态值,以避免过时的闭合捕获的值。

const root = ReactDOM.createRoot(document.getElementById('root'));
const images = ['1','2','3','4','5','6'];

const Thing =()=>{
  const [imageIndex, setImageIndex] = React.useState(0);

  React.useEffect(() => {
    setInterval(() => {
      setImageIndex(prev => (
        prev === images.length - 1 ? 0 : prev + 1
      ));
    }, 1000);
  },[])

  console.log(imageIndex)
  return (
    <div>
      <h1>{images[imageIndex]}</h1>
    </div>
  );
}

  root.render(<Thing  />);


参见 https://codepen.io/drgreen/drgreen/pen/pen/pen/jjpmqrv

请参阅此处 href =“ https://www.freecodecamp.org/news/what-every-every-react-developer-should-know--know-about-about-state/#:%7e:text = what %%20IS%20IS%20Stale%20Stale%20State%20State%20In varable %20 from%20AN%20 outer%20Scope。” rel =“ nofollow noreferrer”>链接几乎相同。

You need to use the second method signature of the useState setter function which gives you the previous state value to avoid the stale closure captured value.

const root = ReactDOM.createRoot(document.getElementById('root'));
const images = ['1','2','3','4','5','6'];

const Thing =()=>{
  const [imageIndex, setImageIndex] = React.useState(0);

  React.useEffect(() => {
    setInterval(() => {
      setImageIndex(prev => (
        prev === images.length - 1 ? 0 : prev + 1
      ));
    }, 1000);
  },[])

  console.log(imageIndex)
  return (
    <div>
      <h1>{images[imageIndex]}</h1>
    </div>
  );
}

  root.render(<Thing  />);


See here https://codepen.io/drGreen/pen/JjpmQrV

Also worth seeing this link which is virtually identical.

记忆消瘦 2025-02-13 07:13:00

在您的情况下,您创建的使用效率仅一次触发。当组件加载时 - 那是因为您没有通过将依赖项添加到使用效率来触发该逻辑何时触发。

现在,由于组件一次呈现一次,因此“ SwitchImage”()仅一次触发一次,因此,它迭代一次,显示IMG并停止。

如果您想了解有关它的更多信息使用效果钩 -

In your case the useEffect which you have created it is only being triggered once; when the component is loading - that is because you did not define when this logic should be triggered by adding dependencies to the useEffect.

Now, since the component renders once, 'switchImage'()' is only being triggered once, hence, it iterates once, display the img and stops.

Here is some good documentation on useEffect if you would like to read more about it Using the Effect Hook - React

????Here is a slightly altered solution where we are using the debounce technique for the timer. SOLUTION????

const root = ReactDOM.createRoot(document.getElementById('root'));

const images = ['????','????','????','????','????','????'];

const DemoComponent = () =>{
const [imageIndex, setImageIndex] = React.useState(0);

//debounce set default 0.3s
const debounce = (func, timeout = 300) =>{
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, timeout);
  };
}

// switch img fn.
const switchImage = () => {
  setImageIndex(imageIndex === images.length - 1 ? 0 : imageIndex + 1)
  return imageIndex;
}

//debounce switchImage and set timer to 1s
const switchImageDebounce = debounce(() => switchImage(),1000);

//useEffect  
React.useEffect(() => {
    switchImageDebounce()
}, [imageIndex]);

return (
  <div>
    <h1>{images[imageIndex]}</h1>
  </div>
);

}

root.render();

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文