在React JS中this.setState的回调中使用this.setState?

che*_*k78 10 javascript callback setstate reactjs

是否可以在this.setState的回调中调用this.setState?

我正在制作一个Roguelike Dungeon并且有一个设置,在this.setState的回调中使用了一个辅助函数,它再次调用this.setState.我的游戏冻结了.

所以我在React组件中有一个对象,它有一个生成随机2D数组映射的方法:

this.Dungeon.Generate();
Run Code Online (Sandbox Code Playgroud)

当游戏开始时,我们在componentDidMount()中调用组件中的以下函数:

componentDidMount: function() {

    this.Dungeon.Generate();

    this.setState({
      board: this.Dungeon.map
    }, function() {

      this.generateGamePlay();

    });

  },
Run Code Online (Sandbox Code Playgroud)

this.generateGamePlay()看起来像这样,基本上生成并将玩家,老板和物品随机放在棋盘上:

generateGamePlay: function() {

var board = this.state.board.slice();

var startPosition = this.randomPosition();

board[startPosition[0]][startPosition[1]] = this.state.player;

var bossPosition = this.randomPosition();

board[bossPosition[0]][bossPosition[1]] = this.state.boss[this.state.dungeonLevel];

this.generateWeapons(this.state.dungeonLevel,board);

this.generateFood(this.state.dungeonLevel, board);

this.generateEnemies(this.state.dungeonLevel, board);

this.setState({
  board: board
});

 },
Run Code Online (Sandbox Code Playgroud)

但是当玩家死亡时,我们再次呼叫以重置游戏:

this.Dungeon.Generate();
        //generate a new dungeon map, available in this.Dungeon.map

        this.setState({
          board: this.Dungeon.map, currentMessage: "Game restarted", player: player, weapon: weapon, dungeonLevel: 0
          }, function(){

                this.generateGamePlay();

          })
Run Code Online (Sandbox Code Playgroud)

但是当我的游戏冻结时.所以我第一次调用this.generateGamePlay()(调用this.setState)它可以工作,但第二次冻结.有人可以帮帮我吗?

Fra*_*ank 2

我会看看您在状态中设置 this.Dungeon.map 的部分。

this.setState({
          board: this.Dungeon.map, currentMessage: "Game restarted", player: player, weapon: weapon, dungeonLevel: 0
          }, function(){

                this.generateGamePlay();

          })
Run Code Online (Sandbox Code Playgroud)

我的猜测是其他东西可能会改变地图对象而不是使用 setstate,因为它是地牢的属性。

来自反应文档

切勿直接改变 this.state,因为之后调用 setState() 可能会替换您所做的改变。将 this.state 视为不可变的。

当您将地图属性传递给 setstate 时,它​​将保留对 this.Dungeon.map 的引用,如果您随后修改该引用,则会导致问题。您应该复制 .map 的内容并将其传递给 state。

您还应该让一个组件负责状态,而不是在不同的函数中多次调用它。来自反应文档

setState() 不会立即改变 this.state ,而是创建一个挂起的状态转换。调用此方法后访问 this.state 可能会返回现有值。

无法保证 setState 调用的同步操作,并且可以对调用进行批处理以提高性能。

由于所有多个 setstate 调用,您的冻结可能是由于渲染方法中的竞争条件造成的。