清除组件间隔的正确方法确实安装在 React 中

Correct way to clear interval in component did mount in React

我试图清除组件在基于 class 的组件中卸载时的时间间隔。我对此做了一些研究,发现在 componentWillUnmount 生命周期函数中,人们将实际函数存储在一个变量中,而不是直接清除间隔。例如:

      componentDidMount() {
        const { stock } = this.props;
// Fetch data once user lands on page
        this.fetchData(stock);
// Fetch data every hour
        setInterval(() => {
          this.fetchData(stock);
          console.log('setInterval ran');
        }, 3600000);
      }
   
    
      componentWillUnmount() {
        const { stock } = this.props;
// Remove interval
        const refreshFetch = clearInterval(this.fetchData(stock));
        console.log('setInterval cleared');
      }
    
      async fetchData(stock) {
        const data = await getAvgPriceHistory(stock);
        if (data && data[stock].length) {
          const dataArray = data[stock].map((arr) => {
            return arr[1];
          }).reverse();
          this.setState({
            data: dataArray,
            isLoaded: true
          });
        } else {
          // straight line if not found.
          this.setState({
            data: [1, 1],
            isLoaded: true
          });
        }
        console.log('Data fetched!');
      }

同时,我习惯于在 componentWillUnmount 函数中执行此操作而无需像这样定义变量:

      componentWillUnmount() {
        const { stock } = this.props;
// Remove interval
       clearInterval(this.fetchData(stock));
        console.log('setInterval cleared');
      }

做其中一个有什么好处吗?

setInterval return一个id。你可以用clearInterval来摧毁它。

https://developer.mozilla.org/en-US/docs/Web/API/setInterval

let intervalId;

...

intervalId = setInterval(fn, time);

...

clearInterval(intervalId);