react如何实现watch
React 中实现类似 Vue 的 watch 功能
在 React 中,没有内置的 watch 功能,但可以通过以下几种方式实现类似 Vue 的监听效果:
使用 useEffect Hook
useEffect 是 React 提供的副作用钩子,可以监听特定依赖项的变化。
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('count changed:', count);
// 在这里执行 count 变化后的逻辑
}, [count]); // 依赖数组,只有 count 变化时才会执行
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
使用自定义 Hook
可以创建一个自定义 Hook 来封装 watch 功能:

import { useEffect, useRef } from 'react';
function useWatch(value, callback) {
const prevValue = useRef(value);
useEffect(() => {
if (prevValue.current !== value) {
callback(value, prevValue.current);
prevValue.current = value;
}
}, [value, callback]);
}
// 使用示例
function MyComponent() {
const [name, setName] = useState('');
useWatch(name, (newVal, oldVal) => {
console.log('Name changed from', oldVal, 'to', newVal);
});
return <input value={name} onChange={(e) => setName(e.target.value)} />;
}
使用第三方库
有一些第三方库提供了更接近 Vue watch 的功能:
-
use-deep-compare-effect: 可以深度比较对象

npm install use-deep-compare-effectimport { useDeepCompareEffect } from 'use-deep-compare-effect'; function MyComponent({ obj }) { useDeepCompareEffect(() => { console.log('obj changed:', obj); }, [obj]); } -
react-use-watch: 专门为 React 设计的 watch 库
npm install react-use-watchimport { useWatch } from 'react-use-watch'; function MyComponent() { const [data, setData] = useState({ count: 0 }); useWatch(data, (newVal, oldVal) => { console.log('data changed:', newVal, oldVal); }); return <button onClick={() => setData({ count: data.count + 1 })}>Increment</button>; }
监听多个状态变化
如果需要同时监听多个状态的变化:
useEffect(() => {
// 当 count 或 name 任一变化时执行
console.log('count or name changed', count, name);
}, [count, name]);
监听 props 变化
组件 props 的变化也可以通过 useEffect 监听:
function MyComponent({ userId }) {
useEffect(() => {
console.log('userId changed:', userId);
// 在这里可以执行数据获取等操作
}, [userId]);
}
注意事项
- 避免在 useEffect 中直接修改依赖的状态,这可能导致无限循环
- 对于复杂对象的监听,默认的浅比较可能不会触发,需要使用深度比较或特定的比较方法
- 清理副作用:如果 useEffect 中有订阅或定时器等操作,需要返回清理函数
useEffect(() => {
const timer = setInterval(() => {
console.log('Timer running');
}, 1000);
return () => {
clearInterval(timer); // 组件卸载时清理
};
}, []);
以上方法提供了在 React 中实现类似 Vue watch 功能的不同方案,可以根据具体需求选择最适合的方式。






