ReactJS组件卸载时图片内存未释放问题求助
Hey Tim, let's figure out how to fix that memory growth issue with your image-containing components!
First, let's break down the problem: when a component with images unmounts, browsers might hold onto image resources in cache or because lingering references prevent garbage collection (GC) from cleaning them up. Plus, I spotted a critical typo in your parent component that's probably making things worse—let's tackle both.
1. Fix the Event Listener Leak in ReactRoot
Looking at your parent component code, there's a typo in the lifecycle method: componentWillUnMount should be componentWillUnmount (note the lowercase m). This mistake means your page-change event listener is never removed when ReactRoot unmounts, keeping the component instance (and its children, like About) from being properly garbage collected.
Here's the corrected code:
export class ReactRoot extends React.Component { // ... rest of your code ... componentWillUnmount(){ // Fixed the lowercase 'm' window.removeEventListener('page-change', this.showPage, false); } // ... rest of your code ... }
2. Clean Up Image References in the About Component
For the image itself, we can explicitly break the resource reference when the component unmounts to help the browser GC free up memory. We'll use a React ref to access the <img> element directly and clear its src attribute.
Update your About component like this:
import React from 'react'; export class About extends React.Component { constructor(props) { super(props); this.imageRef = React.createRef(); // Create a ref for the image } componentWillUnmount() { // Clear the image source to break resource reference if (this.imageRef.current) { this.imageRef.current.src = ''; this.imageRef.current = null; // Explicitly nullify the ref } } render() { return ( <div id='about' > <div className="container"> <div className="row"> <div className="col-md-6"> <h2>title</h2> <p>getting your ideas made</p> </div> <div className="col-md-6"> <img ref={this.imageRef} src="app/images/pic3.png" alt=""/> {/* Attach the ref */} </div> </div> </div> </div> ) } }
Additional Tips
- Use React Strict Mode: Enable
StrictModein your app (wrap your root component in<React.StrictMode>) during development—it will double-mount/unmount components to help catch memory leaks like this early. - Check for Other Lingering References: If you're using any timers, subscriptions, or other global listeners in child components, make sure they're cleaned up in
componentWillUnmount(oruseEffectcleanup functions if you switch to hooks later).
With these changes, your component should properly release memory when unmounted, and you'll see the browser memory usage drop as expected.
内容的提问来源于stack exchange,提问作者Tim Castelijn

