簡體   English   中英

在jsx中替代.map進行迭代?

[英]Alternative to .map in jsx for iterating?

我在我的 jsx 中使用它:

 {item.result && item.result.length
                  ? item.result.map((sale, i) => (sale.month === 1 ? <span key={i}>{sale.itemCount}</span> : 0))
                  : 0}

我正在嘗試返回 sale.itemCount(如果存在)和 sale.month = 1。或者,只返回一個 0。

由於 map 的影響,當應顯示 0 時,它會顯示 map 具有迭代的 0 的數量,例如 000

當結果數組沒有內容或結果數組中不存在匹配的 sale.month 時,如何只顯示一個 0? 該代碼還需要在內聯 jsx 中工作。

我懷疑 map 不是正確的使用方法。

以下是結果數組的兩個示例:

result = [
    {
        "itemCount": 2,
        "month": 7
    },
    {
        "itemCount": -1,
        "month": 8
    },
    {
        "itemCount": 0,
        "month": 9
    }
]
result = []

為了更好地理解完整的代碼,可以在這里看到


我試過把它放在 JSX 之外,並有這個 function:

const searchResultDec = (item) => {
    if (item.result.length === 0) {
      return <span>0</span>; // returns 0 as expected
    }
    if (item.result.length !== 0) {
      item.result.forEach((result) => {
        if (result.month !== 12) {
          return <span>0</span>; // does not return anything
        }
        if (result.month === 12) {
          console.log(result.itemCount); // returns 1 for three items
          return <span>{result.itemCount}</span>; // does not return anything
        }
      });
    }
  };

但是,我在顯示預期結果時再次遇到問題,我已經注意到“不返回任何內容”。

我正在嘗試像這樣顯示結果:

<td>
    {searchResultDec(item)}
</td>

還有一個示例結果數組:

const result = [
    {
        "itemCount": 1,
        "month": 8
    },
    {
        "itemCount": 1,
        "month": 12
    }
]

將您的問題分成獨立的部分,然后將它們放在一起總是一個好主意。 您可能想查看並始終嘗試遵守 單一職責原則 如果你這樣做,你會寫出比 90% 的程序員更好的代碼。 不幸的是,人類擅長將碎片混合在一起。 :-)

話雖如此,您的代碼中有一個邏輯試圖獲取一個月的訂單數。 因此,為此創建一個單獨的 function 是有意義的:

 const result = [ { "itemCount": 2, "month": 7 }, { "itemCount": -1, "month": 8 }, { "itemCount": 0, "month": 9 } ]; function getItemCountForMonth(orderSummary, month) { const monthOrder = orderSummary.find(o => o.month == month); return monthOrder? monthOrder.itemCount: 0; } console.log(getItemCountForMonth(result, 7)); console.log(getItemCountForMonth(result, 8)); console.log(getItemCountForMonth(result, 9)); console.log(getItemCountForMonth(result, 10));

現在你應該可以在你的 JSX 中調用這個 function,如下所示:

<td>
    {getItemCountForMonth(result, 1)}
</td>
<td>
    {getItemCountForMonth(result, 2)}
</td>
<td>
    {getItemCountForMonth(result, 3)}
</td>

等等......甚至可能為此創建一個循環。

Array.map 不是您需要的,因為它將為原始數組中的每個條目創建一個新數組。 這就是為什么它被稱為“地圖”。 它將一個條目映射到一個新條目。

只需返回null而不是 0。

{
  item.result && item.result.length
    ? item.result.map((sale, i) =>
        sale.month === 1 ? (
          <span key={i}>{sale.itemCount}</span>
        ) : null,
      )
    : null
}

嘗試這個:

{item?.result?.length
                  ? item.result.map((sale, i) => 
sale.month === 1? <span key={i}>{sale.itemCount}</span> :0))
                  : 0}

暫無
暫無

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

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