react如何监听state是否变化
监听 React state 变化的常见方法
使用 useEffect HookuseEffect 是监听 state 变化的推荐方式,通过依赖数组指定需要监听的 state 变量。当依赖的 state 变化时,useEffect 内的回调函数会执行。
import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Count changed:', count);
// 执行副作用逻辑
}, [count]); // 仅在 count 变化时触发
return (
<button onClick={() => setCount(count + 1)}>
Increment
</button>
);
}
类组件中的 componentDidUpdate
在类组件中,可以通过 componentDidUpdate 生命周期方法监听 state 变化。通过比较 prevState 和当前 state 实现精确监听。
class Example extends React.Component {
state = { count: 0 };
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
console.log('Count changed:', this.state.count);
}
}
render() {
return (
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
);
}
}
自定义 Hook 封装监听逻辑
对于需要复用的监听逻辑,可以封装成自定义 Hook。例如,创建一个监听 state 变化并执行回调的 Hook:
function useStateChangeListener(state, callback) {
const prevStateRef = useRef(state);
useEffect(() => {
if (prevStateRef.current !== state) {
callback(state, prevStateRef.current);
prevStateRef.current = state;
}
}, [state, callback]);
}
// 使用示例
function App() {
const [value, setValue] = useState('');
useStateChangeListener(value, (newVal, oldVal) => {
console.log(`Value changed from ${oldVal} to ${newVal}`);
});
}
使用 useRef 存储上一次的值
通过 useRef 保存 state 的旧值,结合 useEffect 实现变化对比。适用于需要同时访问新旧值的场景。
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
function Example() {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
useEffect(() => {
if (prevCount !== undefined && prevCount !== count) {
console.log(`Count changed from ${prevCount} to ${count}`);
}
}, [count, prevCount]);
}
注意事项
- 性能优化:避免在
useEffect中执行昂贵计算,必要时使用useMemo或useCallback优化。 - 依赖数组:确保
useEffect的依赖数组包含所有需要监听的变量,否则可能导致逻辑错误。 - 避免无限循环:在监听回调中更新 state 需谨慎,可能触发重新渲染循环。







