【发布时间】:2017-05-23 12:18:39
【问题描述】:
是否可以在this.setState的回调中调用this.setState?
我正在制作一个 Roguelike Dungeon 并且有一个设置,在 this.setState 的回调中使用了一个辅助函数,它再次调用 this.setState。我的游戏此时卡住了。
所以我在 React 组件中有一个对象,它具有生成随机二维数组映射的方法:
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)时它可以工作,但第二次它冻结了。谁能帮帮我?
【问题讨论】:
-
是的,您可以在另一个
setState()的回调中调用setState()。冻结很可能与回调本身无关。
标签: javascript reactjs callback setstate