将图像SRC与来自阵列的图像在React的间隔上进行
这应该很简单,但是从结果中我一直保持怪异的行为。
基本上,我有一系列图像:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
usestate
设置器函数的第二种方法签名,该函数为您提供了上一个状态值,以避免过时的闭合捕获的值。参见 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.See here https://codepen.io/drGreen/pen/JjpmQrV
Also worth seeing this link which is virtually identical.
在您的情况下,您创建的使用效率仅一次触发。当组件加载时 - 那是因为您没有通过将依赖项添加到使用效率来触发该逻辑何时触发。
现在,由于组件一次呈现一次,因此“ 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????
}
root.render();