【问题标题】:Empty array setState using push method in React在 React 中使用 push 方法的空数组 setState
【发布时间】:2020-04-18 11:52:01
【问题描述】:

我尝试将名为mendatory1mendatory2 的特定字符串推入状态中的空数组中。

class SignUp extends React.Component {
  constructor() {
    super();
    this.states = {
      box1: false,
      box2: false,
      box3: false,
      box4: false,
      agreeBox: []
    };
  }
}

- Code in image here:

onClick 事件发生时,SingleClicked 函数激活并将输入检查值从 false 更改为 true,这意味着输入的复选框类型被勾选。

此时我想通过setState更新一个空数组的状态!

SingleClicked = e => {
  console.dir(e.target);
  if (e.target.className === "serviceTerm") {
    this.setState({
      box1: !this.state.box1,
      agreeBox: !this.state.box1
        ? this.state.agreeBox.push("mendatory1")
        : this.state.agreeBox
   });
  }
  if (e.target.className === "InfoSecurity") {
    this.SecondClicked(e);
  }
  if (e.target.className === "PromotionSms") {
    this.ThirdClicked(e);
  }
  if (e.target.className === "PromotionMail") {
    this.FourthClicked(e);
  }
};

- Code in image here:

如果我点击另一个复选框,onClick 事件函数 'SingleClicked' 将调用 'SecondClicked' 函数,该函数会将检查的输入值从 false 更改为 true。

这里,我给出了相同的逻辑代码,但是当onClick事件发生时会报错:

【问题讨论】:

标签: arrays reactjs push setstate


【解决方案1】:

您正在尝试直接改变数组状态,这会导致错误。 您可以使用扩展运算符轻松更新状态。这可以在您的 SingleClicked 函数中:

const agreeBox = !this.state.box1 ?
   [...this.state.agreeBox, 'mendatory2'] : [...this.state.agreeBox];
this.setState({
  box1: !this.state.box1,
  agreeBox,
});

【讨论】:

    【解决方案2】:

    您的错误源于您第一次设置状态。主要问题是:

    this.state.agreeBox.push("mendatory1");
    

    .push() 做了两件事,它将"mendatory1" 添加到您的agreeBox 数组中,然后返回 数组的长度以及添加的字符串。然后您继续将您的agreeBox 属性设置为等于该数字。

    所以,当你再次尝试推入agreeBox 时,它实际上是一个数字,而不是一个数组。要解决此问题,您可以使用 .concat() 而不是 .push()。这不会像 .push() 那样就地修改 agreeBox,而是返回一个新数组,您可以在 setState() 中设置该数组:

    this.state.agreeBox.concat("mendatory1");
    

    【讨论】:

      猜你喜欢
      • 2015-07-11
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-17
      相关资源
      最近更新 更多