所以我创建了一个Json文件的ID和著名人物的图像。现在我想从Json文件中获得一个随机图像并显示它。
到目前为止,我尝试了这个,但我得到一个"Uncaught TypeError: Cannot read properties of undefined (reading 'image')。
import images from "../Index.json"
function Celeb() {
const [image, setImage] = useState();
let random = images[Math.floor(Math.random() * images.length)];
const handleNext = () => {
console.log(images[1].image);
setImage(images[random].image);
}
return (
<div className='celeb'>
<div className='celeb_buttons'>
<button className='play_button' onClick={handleNext}>Next</button>
</div>
<div className='pic'>
<img src={image} />
</div>
</div>
如果我将setImage(images[random].image)中的random替换为0,例如,我将从Json文件中获得第一个图像元素,但我不能使用random。
random
是一个图像,但您稍后试图将其用作数字。
import images from "../Index.json"
function Celeb() {
const [image, setImage] = useState();
const handleNext = () => {
// Generate a random index in the images array
let random = Math.floor(Math.random() * images.length);
// Use the random index to access the correct object in the images array
// and set the image state to the value of the image property
setImage(images[random].image);
}
return (
<div className='celeb'>
<div className='celeb_buttons'>
<button className='play_button' onClick={handleNext}>Next</button>
</div>
<div className='pic'>
<img src={image} />
</div>
</div>
)
}
random
已经是一个图像。Math.floor(Math.random() * images.length)
部分生成一个随机索引。
我没有看到json文件的结构,但我猜你必须将设置部分更改为
setImage(random.image);