React类组件中为何用this.定义函数/变量?技术疑问
Answers to Your React Class Component Questions
Hey there! Great questions—these are super common points of confusion when getting started with React class components, so let's break them down clearly:
1. Why do we need to use this. when defining/calling functions in class methods?
In ES6 class components (which you're working with here), this refers to the current instance of your component. Here's why it's essential:
- When you define a method like
tick()in your class, it's actually attached to the component's prototype (a blueprint for all instances of your component). To access that method from inside another class method (likecomponentDidMount), you needthisto reference the specific component instance that's running right now. Withoutthis., JavaScript won't know where to find thetickmethod and will throw an error. - If you're creating a new function inside a class method and want to access it later from another method, you need to attach it to
thisto make it part of the instance's properties. Otherwise, it's just a local variable that disappears once the current method finishes running.
2. Why do we need to assign setInterval's return value to this.timerID instead of just calling setInterval directly?
The short answer: to clean up the timer when the component unmounts.
Let's break this down:
setIntervalreturns a unique ID that identifies the timer it creates. If you don't save this ID, you have no way to stop the timer later.- React components have a lifecycle method called
componentWillUnmountthat runs right before the component is removed from the DOM. This is where you should clean up ongoing side effects (like timers, event listeners, or API subscriptions) to avoid memory leaks or errors. - By saving the timer ID to
this.timerID, you can access it incomponentWillUnmountand callclearInterval(this.timerID)to stop the timer. If you skip saving the ID, the timer will keep running even after the component is gone—this can lead to errors (like trying to callthis.setStateon an unmounted component) and waste system resources.
Here's what the complete cleanup code looks like:
componentDidMount() { this.timerID = setInterval(() => this.tick(), 1000); } componentWillUnmount() { clearInterval(this.timerID); // Stops the timer when the component is removed }
Without this.timerID, you couldn't reference that specific timer to clear it—you'd be stuck with a timer that runs indefinitely (or until the page reloads).
内容的提问来源于stack exchange,提问作者user8501573
相关产品推荐
相关产品推荐

