繁体   English   中英

setState回调函数没有被调用?

[英]setState callback function is not getting called?

我是React的新手。 在这里,我有一个选择所有元素的复选框。 单击后,我调用一种方法:

handleCheckBox = (event) => {
  if (event.currentTarget.checked) {
    console.log("calling this");
    const updates = {};
    for (const item of [...this.props.untracked.content]) {
      updates[item.resumeId] = "unTracked";
    }
    for (const item of [...this.props.tracked.content]) {
      updates[item.resumeId] = "tracked";
    }
    this.setState(oldState => ({
      selectedValue: {
        ...oldState.selectedValue,
        ...updates,
      }
    }, () => {
      console.log("going in this");
    }));
  } else {
    const reset = {};
    this.setState({
      selectedValue: {
        ...reset
      }
    })
  }
}

当我单击复选框时,它将选择所有值以及它们各自的复选框。 这样, going in this控制台中打印出来。 现在,如果我单击相应的复选框一个或两个,然后如果我尝试单击在其上调用给定方法的复选框,那么该时间不会被调用。

因此,此时没有调用call函数。 因此,是否有任何原因可能导致它无法调用?

this.setState(oldState => ({
  selectedValue: {
    ...oldState.selectedValue,
    ...updates,
  }
}, () => {
  console.log("going in this");
}));

相当于

this.setState(oldState => () => {
  console.log("going in this");
});

因为逗号运算符 您可能打算将两个参数传递给调用,如下所示:

this.setState(oldState => ({
  selectedValue: {
    ...oldState.selectedValue,
    ...updates,
  }
}), () => {
  console.log("going in this");
});

注意括号的放置方式不同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM