Answer the question
In order to leave comments, you need to log in
What's wrong with the timer?
Example from tutorial:
var Timer = React.createClass({
getInitialState: function() {
return {
seconds: 0
};
},
componentDidMount: function() {
this.timer = setInterval(this.tick, 1000);
},
tick: function() {
this.setState({ seconds: this.state.seconds + 1 });
},
componentWillUnmount: function() {
clearInterval(this.timer);
},
render: function() {
return (
<h4> Уже прошло {this.state.seconds} секунд </h4>
);
}
});
ReactDOM.render(
<Timer />,
document.getElementById('mount-point')
);
export default class Timer extends Component {
constructor(props) {
super(props);
this.state = {
seconds: 0
}
}
componentDidMount() {
this.timer = setInterval(this.tick, 1000);
}
tick() {
this.setState({ seconds: this.state.seconds + 1 });
}
componentWIllUnMount() {
clearInterval(this.timer);
}
render(){
return(
<h4>Уже прошло {this.state.seconds} секунд</h4>
)
}
}
Answer the question
In order to leave comments, you need to log in
When using React.createClass, all methods in the component are automatically bound. Therefore, this is not lost there.
With ES6 classes, this no longer happens. And therefore inside tick this is already lost.
You can fix this with a simple bind:
this.timer = setInterval(this.tick.bind(this), 1000);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question