gpt4 book ai didi

javascript - 父状态不更新子组件

转载 作者:行者123 更新时间:2023-12-03 04:29:22 26 4
gpt4 key购买 nike

情况:

当我通过单击“开始”启动模拟时,我的“清除”按钮应该会停止它。但是当我点击“清除”时,什么也没有发生。为什么以及如何修复它?

<小时/>

代码:

游戏.jsx

var Game = createReactClass ({

getInitialState() {
return {
start: false
}
},

handleStartClick() {
this.setState({
start: true
})
},

handleClearClick() {
this.setState({
start: false
})
},

render() {
return (
<div>
<h1>React.js Game of Life</h1>
<div className="buttons">
<button className="btn btn-danger" onClick={this.handleClearClick}>Clear</button>
<button className="btn btn-success" onClick={this.handleStartClick}>Start</button>
</div>
<Board start={this.state.start}/>
</div>
);
}

})

Board.jsx

var Board = createReactClass ({

getInitialState() {
var cellArray = [];
for (var y = 0; y < 40; y++) {
var cells = [];
for (var x = 0; x < 40; x++) {
cells.push(<Cell key={x + y*40} id = {x + y*40} row = {x} column={y} />);
}
cellArray.push(cells);
}
return {
array: cellArray
}
},

render() {

var rows = [];
for (var y = 0; y < 40; y++) {
var cells = [];
for (var x = 0; x < 40; x++) {
cells.push(<Cell start= {this.props.start} array={this.state.array} key={x + y*40} id = {x + y*40} row = {x} column={y} />);
}
rows.push(<tr key={y}>{cells}</tr>);
}
return <table><tbody>{rows}</tbody></table>;

}

})

Cell.jsx

componentWillReceiveProps(nextProps) {

nextProps.array[nextProps.id] = this;

var evolution;

if(nextProps.start && this.state.started == false) {
evolution = setInterval(() => {
this.life(nextProps);
console.log("DYING:"+this.state.dying);
this.setState({
selected: !this.state.dying
});
}, 500);
this.setState({
started: true
})
}
else {
clearInterval(evolution);
this.setState({
started: false
})
}
},

最佳答案

您应该将进化间隔保存到状态中,以便在新 Prop 出现时取消它时可以访问它。

if(nextProps.start && this.state.started == false) {
let evolution = setInterval(() => {
this.life(nextProps);
console.log("DYING:"+this.state.dying);
this.setState({
selected: !this.state.dying
});
}, 500);
this.setState({
started: true,
evolution
})
}
else {
clearInterval(this.state.evolution);
this.setState({
started: false
})
}

关于javascript - 父状态不更新子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43557260/

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