React中的定时图像转盘不工作



所以我对React并不完全陌生,但这让我很失望,它看起来很简单,但我就是无法让它发挥作用。

我想浏览一组图像,并在当前索引处显示图像。控制台中的一切都按预期和意图运行,即我看到了正确的索引和img url。

但是显示的图像没有改变,我只是不明白为什么,但我在图像[0]处看到了第一个图像,所以这很有效。我还想补充一点,我在谷歌上搜索过,没有任何帮助,甚至试过副驾驶,我基本上给了我这个,所以现在我带着我的第一个问题来了。谢谢

这是我的代码:

import { useEffect } from 'react';
import shoe_1 from "../images/shoe_nr_1.jpg";
import shoe_2 from "../images/shoe_nr_2.jpg";
import shoe_3 from "../images/shoe_nr_3.jpg";
import shoe_4 from "../images/shoe_nr_4.jpg";
import shoe_5 from "../images/shoe_nr_5.jpg";
import shoe_6 from "../images/shoe_nr_6.jpg";
function Gallery() {
const images = [shoe_1, shoe_2, shoe_3, shoe_4, shoe_5, shoe_6];

let newImage = images[0];
let i = 0;
const gallery = () => {
if (i < images.length) {
newImage = images[i];
i++;
console.log(i);
console.log(newImage)
} else {
i = 0;
newImage = images[i];
};
setTimeout(gallery, 3000);
};
useEffect(() => {
gallery();
})
return (
<div className="w-full mx-auto h-4/6 lg:h-5/6 bg-slate-400">
<div className="h-full w-full" style={{ backgroundImage: `url("${newImage}")` }}></div>
</div>
)
}
export default Gallery

当组件中的数据需要更改时,使用useState挂钩


import { useEffect, useState } from "react"
import shoe_1 from "../images/shoe_nr_1.jpg"
import shoe_2 from "../images/shoe_nr_2.jpg"
import shoe_3 from "../images/shoe_nr_3.jpg"
import shoe_4 from "../images/shoe_nr_4.jpg"
import shoe_5 from "../images/shoe_nr_5.jpg"
import shoe_6 from "../images/shoe_nr_6.jpg"
function Gallery() {
const [images, setImages] = useState([
shoe_1,
shoe_2,
shoe_3,
shoe_4,
shoe_5,
shoe_6,
])
const [index, setIndex] = useState(0)
useEffect(() => {
if (images.length) {
const timeoutId = setTimeout(() => {
setIndex((index + 1) % images.length)
}, 3000)
return () => clearTimeout(timeoutId)
}
return () => {}
}, [index])
return (
<div className="w-full h-screen mx-auto  lg:h-5/6 bg-slate-400">
<div
className="min-h-full w-full"
style={{ backgroundImage: `url("${images[index]}")` }}
></div>
</div>
)
}
export default Gallery

编辑:更新代码

import { useEffect, useState } from 'react';
import shoe_1 from "../images/shoe_nr_1.jpg";
import shoe_2 from "../images/shoe_nr_2.jpg";
import shoe_3 from "../images/shoe_nr_3.jpg";
import shoe_4 from "../images/shoe_nr_4.jpg";
import shoe_5 from "../images/shoe_nr_5.jpg";
import shoe_6 from "../images/shoe_nr_6.jpg";
function Gallery() {
const images = [shoe_1, shoe_2, shoe_3, shoe_4, shoe_5, shoe_6];
const [newImage, setNewImage] = useState(images[0]);

let i = 0;
const gallery = () => {
if (i < images.length) {

setNewImage(images[i]);
i++;
console.log(i);
console.log(newImage)
} else {
i = 0;
setNewImage(images[i]);
};
setTimeout(gallery, 3000);
};
useEffect(() => {
gallery();
})
return (
<div className="w-full mx-auto h-4/6 lg:h-5/6 bg-slate-400">
<div className="h-full w-full" style={{ backgroundImage: `url("${newImage}")` }}></div>
</div>
)
}
export default Gallery

好的,所以曲线球,我没有把依赖项[]放在useEffect中,因为一些扩展告诉我不需要它;ish";有了这些。现在的问题是skipps 1的数字。从图3到图5等等。但我会自己尝试。谢谢

相关内容

  • 没有找到相关文章

最新更新