MST

星途 面试题库

面试题:React组件卸载时如何清理定时器资源

在React组件中,经常会用到setTimeout或setInterval来设置定时器。当组件卸载时,如果不清理这些定时器,可能会导致内存泄漏等问题。请描述在React组件卸载时,如何正确清理定时器资源,并给出相应的代码示例。
44.3万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试
  1. 使用useEffectuseRef清理定时器
    • 在React函数组件中,可以使用useEffect钩子来设置定时器,并在组件卸载时清理它。useRef用于在组件的多次渲染之间保持一个可变的timer引用。
    • 代码示例如下:
import React, { useEffect, useRef } from'react';

const TimerComponent = () => {
    const timerRef = useRef(null);

    useEffect(() => {
        timerRef.current = setTimeout(() => {
            console.log('定时器触发');
        }, 2000);

        return () => {
            if (timerRef.current) {
                clearTimeout(timerRef.current);
            }
        };
    }, []);

    return (
        <div>
            <p>这是一个包含定时器的组件</p>
        </div>
    );
};

export default TimerComponent;
  1. 对于setInterval同理
    • 假设我们要设置一个每秒打印一次日志的setInterval,并在组件卸载时清理。
    • 代码示例如下:
import React, { useEffect, useRef } from'react';

const IntervalComponent = () => {
    const intervalRef = useRef(null);

    useEffect(() => {
        intervalRef.current = setInterval(() => {
            console.log('间隔定时器触发');
        }, 1000);

        return () => {
            if (intervalRef.current) {
                clearInterval(intervalRef.current);
            }
        };
    }, []);

    return (
        <div>
            <p>这是一个包含间隔定时器的组件</p>
        </div>
    );
};

export default IntervalComponent;

在类组件中,可以在componentDidMount中设置定时器,在componentWillUnmount中清理定时器。例如:

import React, { Component } from'react';

class TimerClassComponent extends Component {
    timer = null;

    componentDidMount() {
        this.timer = setTimeout(() => {
            console.log('定时器触发');
        }, 2000);
    }

    componentWillUnmount() {
        if (this.timer) {
            clearTimeout(this.timer);
        }
    }

    render() {
        return (
            <div>
                <p>这是一个类组件中的定时器示例</p>
            </div>
        );
    }
}

export default TimerClassComponent;

对于setInterval在类组件中的使用和清理也是类似的,在componentDidMount设置setInterval,在componentWillUnmount清理:

import React, { Component } from'react';

class IntervalClassComponent extends Component {
    interval = null;

    componentDidMount() {
        this.interval = setInterval(() => {
            console.log('间隔定时器触发');
        }, 1000);
    }

    componentWillUnmount() {
        if (this.interval) {
            clearInterval(this.interval);
        }
    }

    render() {
        return (
            <div>
                <p>这是一个类组件中的间隔定时器示例</p>
            </div>
        );
    }
}

export default IntervalClassComponent;