[英]React does not re-render child component on setState()
I am really new to react and hence to not quite understand all of the concepts, but as far as i understand, setState() should re-render all affected components.我真的很陌生,因此不太了解所有概念,但据我了解, setState() 应该重新渲染所有受影响的组件。 After googling around and trying for an hour i can't find something to make my code work:在谷歌搜索并尝试了一个小时后,我找不到让我的代码工作的东西:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fighting: false,
health: 100,
gold: 0,
msgs: ["","","",""],
feed: ["","","",""]
};
var intervalFighting;
this.newFeed = this.newFeed.bind(this);
this.newMsg = this.newMsg.bind(this);
this.fighting = this.fighting.bind(this);
this.fightToggle = this.fightToggle.bind(this);
this.healingButton = this.healingButton.bind(this);
}
newFeed(newFeed) {
let tempFeed = [this.state.feed[1],this.state.feed[2],this.state.feed[3]];
this.setState({feed: [tempFeed[0],tempFeed[1],tempFeed[2],newFeed]});
}
newMsg(newMsg) {
let tempMsgs = [this.state.msgs[1],this.state.msgs[2],this.state.msgs[3]];
this.setState({msgs: [tempMsgs[0],tempMsgs[1],tempMsgs[2],newMsg]});
}
fightToggle() {
if(this.state.fighting) {
this.setState({fighting: false});
if(this.intervalFighting != null) clearInterval(this.intervalFighting);
}
else {
this.setState({fighting: true});
this.intervalFighting = setInterval(this.fighting, 1000);
}
}
fighting() {
if(this.state.health == 0) {
clearInterval(this.intervalFighting);
this.setState({fighting: false})
}
if(Math.random() < 0.5) {
console.log("Fighting")
this.setState({health: this.state.health-1})
if(Math.random() < 0.5) this.setState({money: this.state.money+1})
if(Math.random() < 0.1) {
this.newMsg("Wow, you just fought a boss and hence lost 10 health instead of the usual 1.");
this.setState({gold: this.state.gold+20});
}
}
}
healingButton() {
if(this.state.gold >= 10) {
this.setState({health: 100, gold: this.state.gold-10})
this.newFeed("You just healed yourself.")
}
else this.newFeed("You do not have enough money for this.")
}
render() {
return (
<div>
<ItemShop gold = {this.state.gold} />
<OwnHeader />
<Fighting fighting = {this.state.fighting} health = {this.state.health} funcs = {[this.fightToggle, this.healingButton]}/>
<Feed feed = {this.state.feed} />
<Msg msg = {this.state.msgs} />
</div>
)
}
}
The fighting component is just text and two buttons, for whom i give the appropriate onClick functions with funcs.战斗组件只是文本和两个按钮,我为他们提供了适当的 onClick 功能和功能。
Any help is appreciated任何帮助表示赞赏
I figured out the answer out, after a long session with google.在与谷歌进行了长时间的 session 之后,我找到了答案。 It turns out, i needed to use componentWillReceiveProps() in order for this to work.事实证明,我需要使用 componentWillReceiveProps() 才能使其工作。 This link gives a nice explanation. 这个链接给出了一个很好的解释。 I am posting this answer in case anyone has the same problem and then hopefully this can help.如果有人有同样的问题,我会发布这个答案,然后希望这可以提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.