react如何检测
React 检测方法
在 React 中,检测通常涉及状态变化、组件生命周期或用户交互的监控。以下是几种常见的检测方式:
使用 useEffect 钩子
useEffect 是 React 中最常用的检测工具,用于监听依赖项的变化并执行副作用。例如:
useEffect(() => {
console.log('检测到状态变化:', stateValue);
}, [stateValue]); // 仅在 stateValue 变化时触发
使用 useState 和状态更新
通过 useState 设置状态,并在状态更新时触发检测逻辑:
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(prev => prev + 1); // 状态更新会触发重新渲染
};
使用 useRef 检测 DOM 变化
useRef 可以访问 DOM 元素并检测其属性变化:
const ref = useRef(null);
useEffect(() => {
if (ref.current) {
console.log('DOM 元素已挂载:', ref.current);
}
}, []);
return <div ref={ref}>检测目标</div>;
使用 Context API 跨组件检测
通过 useContext 监听全局状态变化:
const value = useContext(MyContext);
useEffect(() => {
console.log('Context 值变化:', value);
}, [value]);
自定义 Hook 封装检测逻辑
将检测逻辑抽象为自定义 Hook 以便复用:
function useDetectChange(value) {
const prevValue = useRef(value);
useEffect(() => {
if (prevValue.current !== value) {
console.log('值从', prevValue.current, '变为', value);
prevValue.current = value;
}
}, [value]);
}
使用错误边界捕获组件错误
通过 componentDidCatch 或 static getDerivedStateFromError 检测子组件错误:

class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.log('检测到错误:', error, info);
}
render() {
return this.state.hasError ? <Fallback /> : this.props.children;
}
}
注意事项
- 避免在
useEffect中直接修改依赖项,否则会导致无限循环。 - 对于性能敏感的检测,可使用
useMemo或useCallback优化。 - 在类组件中,可以使用
componentDidUpdate替代useEffect进行检测。






