简体   繁体   中英

How does 'this' work in Lifecycle methods?

I'm new to react js and have been reading the react docs. In one of the examples, a property (this.timerID) is defined within a lifecycle method (and not in the constructor) and it goes on to be used in another method. I'm having trouble understanding how 'this' in the property helps increase its scope.

The exact document is on, https://reactjs.org/docs/state-and-lifecycle.html . I have been conducting further research about 'this' on https://www.codementor.io/dariogarciamoya/understanding--this--in-javascript-du1084lyn?icn=post-8i1jca6jp&ici=post-du1084lyn . I don't know if its my understanding of ES6 class methods or 'this' that is causing a problem.

class Clock extends Component {
  constructor(){
  ...
  }
  componentDidMount(){
    this.timerID = setInterval(() => this.tick(), 1000)
  }

  componentWillUnmount(){
    clearInterval(this.timerID);
  }
}

Apologies if the question is a bit vague, and any help is appreciated.

this refers to the current instance of the component. So in your example you are setting the interval to your instance.

when you use this keyword with a variable or object then it is referred under the present scope of it. Here the ComponentDidMount is a class lifecycle method and when a variable is assigned with this keyword inside any method of a class , then it means that it is accessing the variable of the Class rather than its own variable.

Here, in your example, the this.timerID variable is used by ComponentDidMount in the scope of the entire class to change the state variable and then render the component. If you use var timerID in ComponentDidMount then it will work as same but if you want to use timerID in other functions then this.timerID will show as undefined as it will only available when mounting and its scope in only inside that method.

The thing is that the everything you are using must have a defined scope.

Here, this keyword just elaborated the scope for the variable to be used inside the class. Thats it, there are just proper ways to manage the variables/objects to get your work done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM