javascript - 为什么“For Loop”只迭代一次,即使参数完全有效?
问题描述
该函数在控制台登录时迭代了 3 次,但在返回图像标签时,它只运行一次!
const imgSources = [
"https://source.unsplash.com/164x130",
"https://source.unsplash.com/144x144",
"https://source.unsplash.com/1920x1080",
];
let fetchImg = () => {
for (let i = 0; i < imgSources.length; i++) {
// console.log(imgSources[i]);
return <Image src={imgSources[i]} height={100} width={100} />;
}
};
我在下面这样使用它:
<div>{fetchImg()}</div>
解决方案
这是因为你在函数中返回
let fetchImg = () => {
for (let i = 0; i < imgSources.length; i++) {
// console.log(imgSources[i]);
return <Image src={imgSources[i]} height={100} width={100} />;
}
};
您应该将这些图像保存在另一个数组中,并使用该数组来访问图像:
let images = [];
let fetchImg = () => {
for (let i = 0; i < imgSources.length; i++) {
// console.log(imgSources[i]);
images.push(<Image src={imgSources[i]} height={100} width={100} />);
}
};
推荐阅读
- php - 如何修复 MessageFormatter 返回格式不正确的日期?
- virtual-machine - 通过 Softlayer API 创建 IBM VM 需要更长的时间
- css - Angular FlexLayout 将所有设备的选择元素和 fab-mini 对齐在同一行,但在边界上未对齐
- excel - 表格列的vba应用格式
- python - 聚类前的标准化
- c# - 在 azure 函数 c#.net 核心中检测图像倾斜角度并修复没有 system.drawing 库
- go - 关闭和发送到通道之间的竞争条件
- python - 我们可以根据python中的'id'过滤字典吗?
- go - 一个结构多个 json 表示
- android - react native 中的平滑闪屏过渡