react如何监听state更新
监听 React state 更新的方法
使用 useEffect 钩子useEffect 是 React 中监听 state 变化的推荐方式。通过将 state 作为依赖项传入 useEffect 的依赖数组,可以在 state 更新时触发副作用逻辑。例如:

import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Count updated:', count);
// 执行其他副作用逻辑
}, [count]); // 依赖数组中指定 count
return <button onClick={() => setCount(count + 1)}>Increment</button>;
}
类组件中的 componentDidUpdate
在类组件中,可以通过 componentDidUpdate 生命周期方法监听 state 或 props 的变化:

class Example extends React.Component {
state = { count: 0 };
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
console.log('Count updated:', this.state.count);
}
}
render() {
return (
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
);
}
}
自定义 Hook 封装逻辑
如果需要复用监听逻辑,可以封装自定义 Hook:
function useStateChangeLogger(state) {
useEffect(() => {
console.log('State changed:', state);
}, [state]);
}
function Example() {
const [value, setValue] = useState('');
useStateChangeLogger(value);
return <input value={value} onChange={(e) => setValue(e.target.value)} />;
}
注意事项
- 避免在
useEffect中直接修改依赖的 state,可能导致无限循环。 - 对于复杂对象或数组类型的 state,需确保依赖项的正确性(如使用深比较或特定字段)。
- 性能敏感场景可考虑使用
useMemo或useCallback优化。






