开发者问题收集

在 React 中将数据数组映射到图像时出现问题

2022-06-05
131

我有一张如下所示的地图

data

我正在使用 .map() 尝试将它们生成为如下图像:

{theLinks.map((item, indx) => (
  <img key={indx} src={item.src} alt={item.label} />
))}

没有返回任何内容,如果我弄乱它,我会得到一个没有有效来源且 alt 为“未知”的单个 img。

2个回答

确保在 return 函数之后或内部添加映射数组 theLinks
例如, 这将不起作用

export default function App() {
  const theLinks = [
    { lable: "Daily Mix", src: "https://flif.info/example-images/fish.png" },
    { lable: "Legit", src: "https://flif.info/example-images/fish.png" },
    { lable: "SCL", src: "https://flif.info/example-images/fish.png" }
  ];

  {theLinks.map((item, indx) => (
        <img
          style={{ width: "50%", border: "1px solid #ccc" }}
          key={indx}
          src={item.src}
          alt={item.label}
        />
  ))}
}

解决方案 1
这将起作用(同时渲染映射数组和其他元素):

export default function App() {
  const theLinks = [
    { lable: "Daily Mix", src: "https://flif.info/example-images/fish.png" },
    { lable: "Legit", src: "https://flif.info/example-images/fish.png" },
    { lable: "SCL", src: "https://flif.info/example-images/fish.png" }
  ];

  return (
    <>
      <h1> thanks Phil for your suggestion! </h1>
      {theLinks.map((item, indx) => (
        <img
          style={{ width: "50%", border: "1px solid #ccc" }}
          key={indx}
          src={item.src}
          alt={item.label}
        />
      ))}
      ;
    </>
  );
}

解决方案 2
这将起作用(仅渲染映射数组)

export default function App() {
  const theLinks = [
    { lable: "Daily Mix", src: "https://flif.info/example-images/fish.png" },
    { lable: "Legit", src: "https://flif.info/example-images/fish.png" },
    { lable: "SCL", src: "https://flif.info/example-images/fish.png" }
  ];

  return theLinks.map((item, indx) => (
    <img
      style={{ width: "50%", border: "1px solid #ccc" }}
      key={indx}
      src={item.src}
      alt={item.label}
    />
  ));
}
omar
2022-06-05

尝试一下

{theLinks.map((item, indx) => { return ( <img key={indx} src={item.src} alt={item.label} /> ); })

Vishwaraj Kamble
2022-06-05