簡體   English   中英

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

[英]Using this.setState in the callback of this.setState in React JS?

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

我正在制作一個Roguelike Dungeon並且有一個設置,在this.setState的回調中使用了一個輔助函數,它再次調用this.setState。 我的游戲凍結了。

所以我在React組件中有一個對象,它有一個生成隨機2D數組映射的方法:

this.Dungeon.Generate();

當游戲開始時,我們在componentDidMount()中調用組件中的以下函數:

componentDidMount: function() {

    this.Dungeon.Generate();

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

      this.generateGamePlay();

    });

  },

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

 },

但是當玩家死亡時,我們再次呼叫以重置游戲:

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)它可以工作,但第二次凍結。 有人可以幫幫我嗎?

我會看看你正在設置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.state看作是不可變的。

當你將map屬性傳遞給setstate時,它將保留對this.Dungeon.map的引用,如果你隨后修改將導致問題。 你應該復制.map的副本並將其傳遞給state。

您還應該制作一個負責狀態的組件,而不是在不同的功能中多次調用它。 來自反應文檔

setState()不會立即改變this.state,但會創建掛起狀態轉換。 調用此方法后訪問this.state可能會返回現有值。

無法保證對setState的調用進行同步操作,並且可以對調用進行批處理以提高性能。

由於所有多個setstate調用,你的凍結可能來自render方法中的競爭條件。

就像弗蘭克的代碼一樣,我有這個:

this.setState( state => {
  state.board = this.Dungeon.map
  return state
})

我希望這對你來說很方便,或者說我做錯了,或者誤解了你的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM