【问题标题】:How to check multiple states in reactjs on an if statement?如何在 if 语句上检查 reactjs 中的多个状态?
【发布时间】:2020-07-04 05:32:52
【问题描述】:

必须有一种更清洁的方法来做到这一点我只是想不出一个原因这看起来很糟糕我想在 if 语句 atm 中检查多个状态这是我能想到的让它工作的唯一方法。我认为某种形式的数组可能会起作用,但我想不出如何做出反应?

calculate_bmi = () => {
  if (this.state.Gender !== "") {
    if (this.state.Goal !== "") {
      if (this.state.Weight !== "") {
        if (this.state.Height !== "") {
          if (this.state.Age !== "") {
            console.log(
              this.state.Gender,
              this.state.Goal,
              this.state.Weight,
              this.state.Height,
              this.state.Age
            );
          } else {
            alert(
              "Please enter your Height, Weight and Age so we can achieve your goals!"
            );
          }
        } else {
          alert(
            "Please enter your Height, Weight and Age so we can achieve your goals!"
          );
        }
      } else {
        alert(
          "Please enter your Height, Weight and Age so we can achieve your goals!"
        );
      }
    } else {
      alert(
        "Please enter your Height, Weight and Age so we can achieve your goals!"
      );
    }
  } else {
    alert(
      "Please enter your Height, Weight and Age so we can achieve your goals!"
    );
  }
};

【问题讨论】:

  • 你知道 JS 中的 &&|| 运算符吗?
  • 我试过 && 它似乎没有用,但我不知道 '||'这是什么意思?
  • ||表示“或”,如 if (this.state.Gender !== "" || this.state.Goal !== "") { // code }
  • 有一个很棒的库叫做 lodash 可以帮助你。例如,以下答案显示了如何测试对象的值是否为空。将 _.pick 与以下答案链接是检查属性列表是否为空的一种巧妙方法。 stackoverflow.com/a/54447355/7034696

标签: javascript reactjs


【解决方案1】:
calculate_bmi = () => {
  if (
    this.state.Gender !== "" &&
    this.state.Goal !== "" &&
    this.state.Weight !== "" &&
    this.state.Height !== "" &&
    this.state.Age !== ""
  ) {
    console.log(
      this.state.Gender,
      this.state.Goal,
      this.state.Weight,
      this.state.Height,
      this.state.Age
    );
  } else {
    alert(
      "Please enter your Height, Weight and Age so we can achieve your goals!"
    );
  }
}  

【讨论】:

  • 辛苦了,谢谢我确定这是我之前尝试过的,但显然不是谢谢!
【解决方案2】:

实现它的简单方法。

const check = () => {
  const { Gender, Goal, Weight, Height, Age } = this.state;
  if ([Gender, Goal, Weight, Height, Age].every(x => x !== "")) {
    console.log(list.join('\n'));
  } else {
    alert("Please enter your Height, Weight and Age so we can achieve your goals!");
  }
};

如果您需要包含优先级,这是我的第一个想法。

const check = (state) => {
  const checkList = ['Gender', 'Goal', 'Weight', 'Height', 'Age'];
  const isAllGood = !checkList.some(x => {
    const flg = state[x] === '';
    if (flg) {
      alert(`Please enter your ${x} so we can achieve your goals!`);
    }
    return flg;
  });
  if (isAllGood) {
    console.log(state);
  }
}

【讨论】:

  • 非常感谢您,我现在已经开始工作了,但我们非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2014-12-27
  • 1970-01-01
  • 1970-01-01
  • 2012-12-13
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多