【问题标题】:Why is my array not updated in the state in React? [duplicate]为什么我的数组在 React 中的状态没有更新? [复制]
【发布时间】:2019-03-04 20:39:30
【问题描述】:

在调用this.setState 之后,talents 属性仍然保持旧值:

onTalentModalCheckboxChange(e) {
  debugger;
  var talent = JSON.parse(e.target.dataset.talent);
  talent.checked = !talent.checked;

  if (this.maximumSelectedTalentsReached() && talent.checked) return;

  const talentIndex = this.state.talents.findIndex(t => t.Id == talent.Id);
  let updatedTalents = [...this.state.talents];
  updatedTalents[talentIndex] = talent;

  this.setState({ talents: updatedTalents });

  // this method (setSearchResultsTotal) uses this.state.talents, 
  // but the talent that is updated here, is not updated. 
  // It still has the 'old' checked value
  this.setSearchResultsTotal();
}

talents 属性包含 Talent 对象列表,这些对象都具有 checked 属性。我的问题是在设置更新的天赋对象时

我在这里错过了什么?

【问题讨论】:

标签: reactjs


【解决方案1】:

setState 是异步的,这意味着更改不会立即发生。因此,任何使用状态的函数都需要setState 调用完成后调用。有两种方法可以做到这一点:如果this.state.talentsprevState.talents 不同,则使用componentDidUpdate 触发函数。或者,使用setState 回调调用函数:

onTalentModalCheckboxChange(e) {
  debugger;
  var talent = JSON.parse(e.target.dataset.talent);
  talent.checked = !talent.checked;

  if (this.maximumSelectedTalentsReached() && talent.checked) return;

  const talentIndex = this.state.talents.findIndex(t => t.Id == talent.Id);
  let updatedTalents = [...this.state.talents];
  updatedTalents[talentIndex] = talent;

  // Only call this.setSearchResultsTotal after state has finished updating
  this.setState({ talents: updatedTalents }, () => this.setSearchResultsTotal(); );

}

【讨论】:

    【解决方案2】:

    this.setState({ talents: updatedTalents }, () => {
      this.setSearchResultsTotal();
    });

    尝试像这样调用你的方法,它会工作

    【讨论】:

    • 为了解释起见,这样做是注册一个匿名回调以确保在状态更新后调用setSearchResultsTotal
    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 2021-12-11
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 2019-10-23
    相关资源
    最近更新 更多