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.

full code

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);
有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top