gpt4 book ai didi

reactjs - 运行函数来更新组件构造函数(及更高版本)的状态

转载 作者:行者123 更新时间:2023-12-03 14:13:25 25 4
gpt4 key购买 nike

我正在尝试编写一个小战斗卡牌游戏作为学习练习,以理解 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>
);
};
};

但是,当我创建应用程序组件时,出现错误

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.

我尝试阅读已安装/未安装的组件,但我似乎无法弄清楚这里发生了什么。我想我需要在安装应用程序时在渲染过程中稍后调用 drawHand 方法 - 是否有一个事件或类似的事件我可以用于此目的?

最佳答案

构造函数在组件挂载到 DOM 之前运行。

所以你想要的是执行 componentDidMount 中的方法生命周期方法。

像这样

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

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

componentDidMount() {
this.drawHand();
}

render() {
return (
<div className="row">
{this.state.hero.hand.join(',')}
</div>
);
};
};

关于reactjs - 运行函数来更新组件构造函数(及更高版本)的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49070453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com