【发布时间】:2018-03-02 13:49:42
【问题描述】:
我正在尝试编写一个小型战斗纸牌游戏作为学习练习,以了解 React,尤其是状态。在游戏中,我希望每回合都可以抽出一张新的牌,所以我创建了一个抽牌的函数,并从构造函数中调用它:
class App extends Component {
constructor() {
super();
this.state = {
hero: {
str: 2,
currentStr: 2,
def: 2,
currentDef: 2,
health: 100,
currentHealth: 74,
moves: 3,
currentMoves: 3,
cards: [1, 1, 1, 2, 2, 2],
draw: 4,
hand: [],
},
};
this.drawHand = this.drawHand.bind(this);
this.drawHand();
}
drawHand() {
let draw = [];
let cards = this.state.hero.cards.slice();
for (let i = 0; i < this.state.hero.draw; i++) {
const min = 0;
const max = cards.length -1;
const position = Math.floor(Math.random() * (max - min + 1)) + min;
const item = cards.splice(position, 1);
draw.push(item[0]);
}
draw = draw.sort();
let hero = {...this.state.hero};
hero.hand = draw;
this.setState({
hero: hero
});
}
render() {
return (
<div className="row">
{this.state.hero.hand.join(',')}
</div>
);
};
};
然而,当我创建 App 组件时,我得到了错误
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.
我尝试阅读已安装/未安装的组件,但我似乎无法弄清楚这里发生了什么。我想我需要在安装 App 后的渲染过程中稍后调用 drawHand 方法 - 请问有什么可以用于此的事件或类似的吗?
【问题讨论】:
标签: reactjs