在onClick方法中反应setState而不更新DOM

时间:2017-08-08 09:20:40

标签: javascript reactjs meteor-react

我正在使用react开发一个简单的游戏战斗动画。为了开始战斗,我有一个onClick事件的按钮:onClick={this.fight.bind(this)}。现在我想在任何时候更改一些状态变量:

import React, { Component } from 'react';
import { ProgressBar, Row, Col } from 'react-bootstrap';
const playerA = {
    _id: 1,
    name: "playerA name",
    life: 100,
    speed: 50,
}
const playerB = {
    _id: 1,
    name: "playerB name",
    life: 100,
    speed: 40,
}

export default class App extends Compornent {

  constructor() {
    super();
      this.state={
        playerA : playerA ,
        playerB : playerB ,
        aLife: 100,
        bLife: 100,
    };
    this.fight = this.fight.bind(this);
  };

  fight(a,b){
    lifeA=this.state.playerA.live;
    lifeB=this.state.playerB.live;
    speedA=this.state.playerA.speed;
    speedB=this.state.playerB.speed;
    dmg = 10
    while (lifeA>0 && lifeB>0) {
      if (speedA > speedb) {
        lifeA = lifeA - dmg;
        setTimeout(() => {
          this.setState({ aLife: lifeA });
        }, 1000);
        speedB = speedB + 10;
      } else {
        lifeB = lifeB - dmg;
        setTimeout(() => {
          this.setState({ bLife: lifeA });
        }, 1000);
        speedA = speedA + 10;
      }
  }
  render() {
    return (
      <Row>
        <ProgressBar bsStyle="success" now={this.state.aLife} srOnly/>
        <ProgressBar bsStyle="success" now={this.state.bLife} srOnly/>
      </Row>
      <Row>
        <Button bsStyle="danger" bsSize="large" onClick={this.fight.bind(this)}>Start Fight</Button>
      </Row>
    );
  }   
}

我的期望是看到进度条每1秒更新一次。但它只更新一次。当战斗功能完成后,执行beein。

2 个答案:

答案 0 :(得分:0)

引用ReactJs official documents,你不必再在render函数中绑定它,因为你已经在构造函数中完成了绑定

<Button bsStyle="danger" bsSize="large" onClick={this.fight.bind(this)}>Start Fight</Button>

应该是

 <Button bsStyle="danger" bsSize="large" onClick={this.fight}>Start Fight</Button>

答案 1 :(得分:0)

我终于通过使用setInterval使用bool条件完全重写while循环来完成此操作:((npcPlayerLife > 0) && (advPlayerLife > 0))然后在条件不再满足时停止。 我有这个帮助的人。