首页 > 解决方案 > 为什么“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>

标签: javascriptarraysreactjsnext.js

解决方案


这是因为你在函数中返回

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} />);
  }
};

推荐阅读