Using this.setState in this.setState callback in React JS?

Is it possible to call this.setState in the callback of this.setState?

I am creating a Dungeon Roguelike and have a setting where a helper function is used in the this.setState callback that calls this.setState again. My game freezes at this point.

So, I have an object in the React component that has a way to generate a random map of a 2D array:

this.Dungeon.Generate();

When the game starts, we call the following function in the component in the DidMount () component:

componentDidMount: function() {

    this.Dungeon.Generate();

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

      this.generateGamePlay();

    });

  },

this.generateGamePlay () looks like this and basically generates and places the player, boss and objects randomly on the board:

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
});

 },

But when the player dies, we again call for a reset game:

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();

          })

. , this.generateGamePlay() ( this.setState), , . - ?

+4
1

, this.Dungeon.map .

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

                this.generateGamePlay();

          })

, - , setstate, Dungeon.

this.state , setState() , . . .

, , this.Dungeon.map, , , . , - .map, , .

, , , .

setState() this.state, . this.state .

setState .

- .

+1
source

Source: https://habr.com/ru/post/1666230/


All Articles