React的isMounted如何使用
isMounted的使用方法
React的isMounted方法曾用于检查组件是否已挂载到DOM中,但该方法已被弃用。官方推荐使用其他方式替代。
替代方案
使用useRef和useEffect组合实现类似功能:
import { useEffect, useRef } from 'react';
function MyComponent() {
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
const checkStatus = () => {
if (isMounted.current) {
console.log('Component is mounted');
}
};
}
类组件替代方案
对于类组件,可以在componentDidMount和componentWillUnmount中设置标志:
class MyComponent extends React.Component {
_isMounted = false;
componentDidMount() {
this._isMounted = true;
}
componentWillUnmount() {
this._isMounted = false;
}
checkStatus() {
if (this._isMounted) {
console.log('Component is mounted');
}
}
}
注意事项
避免在异步操作中直接依赖挂载状态,考虑使用AbortController取消请求。React官方明确表示isMounted是反模式,可能导致内存泄漏。







