簡體   English   中英

如何在 ES6/React 的段落中顯示來自 2 個數組的值

[英]how to display values from 2 arrays in paragraphs in ES6/React

我正在 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 一樣對其進行映射。

我相信您的問題有一個比您目前的方法更簡單的解決方案。 例如,您可以在映射圖像/名稱組件時立即使用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具有什么格式的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM