React autobinds methods defined in the component spec since that's almost always what you want. See this blog post for more details: New in React v0.4: Autobind by Default.
setInterval callback with context
-
03-10-2022 - |
Frage
I started to learn React framework, but actually i am looking on this code from main site and still can't understand it
tick: function() {
this.setState({secondsElapsed: this.state.secondsElapsed + 1});
},
componentDidMount: function() {
this.interval = setInterval(this.tick, 1000);
If i pass this.tick
to setInterval
, then when the timer event is fired under hood and this.tick
is called, it should be probably called in context of window
object, right? If this is true, then the code in tick
function should be wrong, because there is no setState
function on window
object.
var Timer = React.createClass({
getInitialState: function() {
return {secondsElapsed: 0};
},
tick: function() {
this.setState({secondsElapsed: this.state.secondsElapsed + 1});
},
componentDidMount: function() {
this.interval = setInterval(this.tick, 1000);
},
componentWillUnmount: function() {
clearInterval(this.interval);
},
render: function() {
return React.DOM.div({},
'Seconds Elapsed: ', this.state.secondsElapsed
);
}
});
React.renderComponent(Timer({}), mountNode);
Lösung
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow