当前位置: 代码迷 >> JavaScript >> 在设置状态后如何等待反应
  详细解决方案

在设置状态后如何等待反应

热度:55   发布时间:2023-06-07 15:55:15.0

React 16.8(使用类不挂钩)

在一个名为onClick的函数中考虑以下if语句

 if (this.state.opponentIsDead) {
    this.setState({
      disableAttack: 'disabled',
    }, () => {
      this.timer = setTimeout(() => {
        this.props.postFightData({
          train_exp: 100,
          drop_chance: this.state.monster.drop_chance,
          gold_rush_chance: this.state.monster.gold_rush_chance,
          gold_drop: this.state.monster.gold_drop,
        });
      }, 1000);
    });
  }

我想要做的是在发布战斗数据之前等待一秒钟,如果你已经赢??得了战斗,那么超时工作。 但是你可以看到我正在更新状态以禁用按钮。

我想要做的是将超时移动到componentDidUpdate方法,这样组件将重新渲染,按钮将被禁用,我觉得这是错误的方法。

我知道你可以将setState包装在异步函数中,但我也想知道这是不是最好的方法。

目标是禁用按钮,然后等待1秒钟并发布数据。 什么是最好的方法?

这种方法有什么问题?

对于那些可能不知道的人,将调用setState来更新状态,但是不是重新渲染它,而是调用回调函数,因此在计时器倒计时时按钮不会被禁用。

它将在计时器之后被禁用,而不是之前,我之前想要它,而不是之后。

我怀疑还有其他东西导致你发出问题。 这段代码似乎按照你想要的方式工作(或者我误解了)。

- 按钮单击禁用按钮,3秒后出现发布警报

虽然使用componentDidUpdate是推荐的方法..

setState()的第二个参数是一个可选的回调函数,它将在setState完成并重新呈现组件后执行。 通常我们建议使用componentDidUpdate()代替这种逻辑。

这应该做到这一点。

if (this.state.opponentIsDead) {
  this.setState({
    disableAttack: 'disabled',
  });

  window.requestAnimationFrame(() => {
    this.timer = setTimeout(() => {
      this.props.postFightData({
        train_exp: 100,
        drop_chance: this.state.monster.drop_chance,
        gold_rush_chance: this.state.monster.gold_rush_chance,
        gold_drop: this.state.monster.gold_drop,
      });
    }, 1000);
  });
}
  相关解决方案