【问题标题】:how to display values from 2 arrays in paragraphs in ES6/React如何在 ES6/React 的段落中显示来自 2 个数组的值
【发布时间】:2021-10-04 03:59:14
【问题描述】:

我在 React 中使用更大的数组,并希望如下显示:图像/名称图像/名称图像/名称。我有以下代码,但我不知道如何将图像数组映射到它显示它的图像。谢谢

function showProtocolsNames() {
if (supportedVaults) {
  let arr = supportedVaults
    .map((item) => item.protocolName)
    .filter((item, index, arr) => {
      return arr.indexOf(item) == index;
    });

  let arrImages = supportedVaults
    .map((item) => item.protocolKey)
    .filter((item, index, arr) => {
      return arr.indexOf(item) == index;
    });

  let protocolsName = [...new Set(arr)];
  let protocolsImages = [...new Set(arrImages)];
  console.log(protocolsName, protocolsImages);

  return protocolsName.map((vault) => {
    return (
      <>
        {' '}
        <img
          src={getVaultIcon(vault)}
          width="42px"
          height="42px"
          style={{
            marginRight: '12px',
          }}
        />
        <p className="vaults-protocol">{vault}</p>
      </>
    );
  });
}
return null;

}

已解决: 通过一起创建图像和名称的数组,然后像 DBS 在 cmets 中建议的那样对其进行映射。

【问题讨论】:

  • 哦,对不起!我想这样显示:1 嘿 2 hello 3 see ya
  • 是的,请 1 秒
  • 我现在更新了我的问题。我以前没有在这里问过很多问题。非常感谢您的帮助!
  • 那好多了 - 我不这样做 react 所以我帮不上忙
  • protocolNameprotocolKey 映射到两个单独的数组中似乎很奇怪,然后可能需要在getVaultIcon 函数中将它们重新组合在一起。从一开始就建造一个单一的结构不是更好吗?

标签: javascript reactjs ecmascript-6


【解决方案1】:

我相信对于您的问题有一个比您当前的方法更简单的解决方案。例如,您可以在映射图像/名称组件时立即使用supportedVaults 数据,如下所示:

function showProtocolsNames() {
  // added check to ensure there is data inside supportedVaults
  if (supportedVaults.length) {
    // removed the two mapped arrays

    // added index which is generated by map function
    return protocolsName.map((vault, index) => {
      // added div instead of <> in order to include a key, which is required in a map function
      return (
        <div key={`${index}-${vault?.protocolKey}`}>
          {" "}
          <img
            src={getVaultIcon(vault?.protocolKey)} // here we pass protocolKey to the getVaultIcon function
            width="42px"
            height="42px"
            style={{
              marginRight: "12px",
            }}
          />
          {/* here we add protocolName inside the paragraph */}
          <p className="vaults-protocol">{vault?.protocolName}</p>
        </div>
      );
    });
  }

  return null;
}

以上逻辑基于您对问题的描述,假设您需要传递 protocolKey 以在 getVaultIcon 函数中获取保险库图标,而 protocolName 是您需要显示为名称的值。如果我的看法有误,请编辑您的问题以反映更多信息,了解您需要从 supportedVaults 数组中获取哪些确切数据,或者 supportedVaults 具有什么格式。

【讨论】:

  • 您好!这帮助我找到了答案,非常感谢。
  • @Alexandria 很高兴它有所帮助,如果这是您正在寻找的答案,请将其标记为您帖子的答案,否则建议对其进行任何更改或编辑,以便其他人鼓励同样的问题能尽快得到正确答案。
  • 对不起,我会开始在这里提出更好的问题并做得更好。非常感谢您的时间和精力来回答。
猜你喜欢
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多