React中如何监听state的变化
监听state变化的常用方法
在React中,监听state变化可以通过以下几种方式实现:
使用useEffect钩子
import { useState, useEffect } from 'react';
function Component() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Count changed:', count);
// 执行state变化后的操作
}, [count]); // 依赖数组指定要监听的state
return <button onClick={() => setCount(c => c + 1)}>Increment</button>;
}
类组件中使用componentDidUpdate
class Component 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封装监听逻辑
function useWatchState(state, callback) {
const prevStateRef = useRef();
useEffect(() => {
if (prevStateRef.current !== state) {
callback(state, prevStateRef.current);
}
prevStateRef.current = state;
}, [state, callback]);
}
// 使用示例
function Component() {
const [value, setValue] = useState('');
useWatchState(value, (newVal, oldVal) => {
console.log('Value changed from', oldVal, 'to', newVal);
});
}
注意事项
- 避免在useEffect中直接修改所监听的state,这会导致无限循环
- 对于复杂对象类型的state,可能需要深度比较或使用use-deep-compare-effect等库
- 类组件的componentDidUpdate会在每次渲染后触发,需要手动比较prevState和currentState
性能优化
对于频繁更新的state,可以考虑使用useMemo或useCallback来优化相关计算:
const memoizedValue = useMemo(() => computeExpensiveValue(state), [state]);
高级用法
使用useReducer配合context可以实现全局状态监听:
const StateContext = createContext();
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<StateContext.Provider value={{ state, dispatch }}>
<ChildComponent />
</StateContext.Provider>
);
}
function ChildComponent() {
const { state } = useContext(StateContext);
// 监听state的特定部分
}






