尝试使用地图方法代替使用React Typescript的for循环

时间:2019-11-13 16:31:21

标签: javascript reactjs typescript

我正在尝试使用映射方法use而不是使用React Typescript进行以下代码的for循环,但是不起作用

使用for循环的实际代码:

renderFunction(perkProgressData) {
    let tiers = [];
    let currentData = { item: {} }
    const data = perkProgressData.perkProgressData
    if (data && data.program && data.program.tiers) {
      tiers = data.program.tiers
      **for (let i = 0; i < tiers.length; i++) {**
        if (tiers[i].tierPerks[0].perkStatus === "UNCLAIMED" ||
          data.currentTierId === tiers[i].tierId) {
          currentData = { item: tiers[i] }
          break;
        }
      }
    }

尝试使用.map():(不起作用)

renderFunction(perkProgressData) {
    let tiers = [];
    let currentData = { item: {} }
    const data = perkProgressData.perkProgressData
    if (data && data.program && data.program.tiers) {
      tiers = data.program.tiers
      tiers.map((val) => {
        if (val.tierPerks && val.tierPerks[0].perkStatus === "UNCLAIMED" || 
          data.currentTierId === val.tierId) {
            currentData = { item: val }
          }
        });
      }
    }

1 个答案:

答案 0 :(得分:2)

map在这里不是正确的选择,您不需要它创建的新数组。另外,您想尽早停止,map不会停止(除非您抛出错误)。

for循环很好,尽管您可能会考虑使用for-of,因为您不使用索引:

renderFunction(perkProgressData) {
    let tiers = [];
    let currentData = { item: {} };
    const data = perkProgressData.perkProgressData;
    if (data && data.program && data.program.tiers) {
      tiers = data.program.tiers;
      for (const tier of tiers) {
        if (tier.tierPerks[0].perkStatus === "UNCLAIMED" ||
          data.currentTierId === tier.tierId) {
          currentData = { item: tier };
          break;
        }
      }
    }
    // ...

或者在循环后不需要tiers

renderFunction(perkProgressData) {
    let currentData = { item: {} };
    const data = perkProgressData.perkProgressData;
    if (data && data.program && data.program.tiers) {
      for (const tier of data.program.tiers) {
        if (tier.tierPerks[0].perkStatus === "UNCLAIMED" ||
          data.currentTierId === tier.tierId) {
          currentData = { item: tier };
          break;
        }
      }
    }
    // ...

如果您真的想使用数组方法,那么find会很有意义:

renderFunction(perkProgressData) {
    const data = perkProgressData.perkProgressData
    let currentData =
      ( data &&
        data.program &&
        data.program.tiers &&
        data.program.tiers.find(tier =>
          tier.tierPerks[0].perkStatus === "UNCLAIMED" || data.currentTierId === tier.tierId
        )
      ) ||  { item: {} };
    // ...