Reputation: 4491
SITUATION:
When I launch the simulation by clicking on Start, my Clear button is supposed to stop it. But when I click on Clear, nothing happens. Why and how do I fix it ?
CODE:
Game.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
})
}
},
Upvotes: 0
Views: 82
Reputation: 11093
You should save your evolution interval to state so you can access it when the new props come in to cancel it.
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
})
}
Upvotes: 1