【问题标题】:Need map function to run another function only once需要 map 函数只运行一次另一个函数
【发布时间】:2017-09-25 11:53:09
【问题描述】:

我正在运行一个 map 函数,如果满足条件,我希望它返回一个函数,否则,运行另一个函数。

但问题是,当条件不满足时,函数运行的次数与条件为假的次数一样多。我只希望第二个函数只运行一次。

这是我的代码:

  handleVote(name, url) {
    this.props.bandsVoted.map(band => {
      if (band.band_name === name) {
        console.log("it's a match!");
        this.props.dispatch(addVote(band.objectId, band.votes));
      } else {
        console.log("addNewBand just ran");
        this.props.dispatch(addNewBand(name, url));
      }
    });
  }

我正在使用 react、javascript,并且可以使用 lodash。有什么建议吗?谢谢!

编辑:也尝试过,但不起作用

 handleVote(name, url) {
    let runOnce = true;
    this.props.bandsVoted.forEach(band => {
      if (band.band_name === name && runOnce) {
        console.log("it's a match!");
        this.props.dispatch(addVote(band.objectId, band.votes));
        runOnce = false;
      } else if (band.band_name !== name && runOnce) {
        console.log("addNewBand just ran");
        this.props.dispatch(addNewBand(name, url));
        runOnce = false;
      }
    });
  }

【问题讨论】:

  • 您需要添加一个布尔变量,该变量将指向该函数是否已被调用

标签: javascript reactjs lodash


【解决方案1】:

首先,当你想要的只是循环时,使用 map 是错误的。然后只需存储一些标志。这应该适合你:

handleVote(name, url) {
  let matched = false

  this.props.bandsVoted.forEach(band => {
    if (band.band_name === name) {
      console.log("it's a match!");
      matched = true
      this.props.dispatch(addVote(band.objectId, band.votes));
    }
  });

  if (!matched) {
    this.props.dispatch(addNewBand(name, url));
  }
}

【讨论】:

  • this 在 foreach 回调中是否可用?
  • 所以它工作,它不工作。 if (band.band_name === name) 只有在第一个 band_name 匹配时才为真。如果没有立即匹配,它会转到第二个条件,即使有匹配。
  • 如果band. band_name 等于name,@bikedres if (band.band_name === name) 将为真。不确定你的意思“如果它没有立即匹配,它会转到第二个条件,即使有匹配。”。它只会在第一次不匹配后进入第二个条件。
  • @dfsq 如果绝对不匹配,我希望它进入第二个条件。到目前为止,该代码同时运行addVote 和addNewBand。布尔值有帮助,所以我尝试了一些不同的东西,比如......(用我正在尝试的代码更新了我的帖子)
  • @bikedres 所以你想addNewBand 只有在根本没有匹配的情况下?对于所有匹配addVote?然后检查更新的答案。您需要将addNewBand 移出循环。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多