React 中监听 state 变化
文章类型:React
发布者:hp
发布时间:2025-02-28
1:通过useEffect
通过依赖项数组监听特定 State 的变化,触发副作用操作
import { useState, useEffect } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('count 变化:', count);
// 自定义操作(如发起请求、更新其他状态等)
}, [count]); // 依赖项为 count
return <button onClick={() => setCount(count + 1)}>+1</button>;
}
2:自定义回调函数
若需将 State 变化暴露给父组件,可通过 Props 传递回调函数
// 父组件
function Parent() {
const handleChildStateChange = (newValue) => {
console.log('子组件 State 更新:', newValue);
};
return <Child onStateChange={handleChildStateChange} />;
}
// 子组件
function Child({ onStateChange }) {
const [value, setValue] = useState('');
return <input onChange={(e) => { setValue(e.target.value); onStateChange(e.target.value); }} />;
}
1:生命周期方法 componentDidUpdate:
在类组件中,通过比较新旧 State 执行操作
class MyComponent extends React.Component {
state = { count: 0 };
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
console.log('count 变化:', this.state.count);
}
}
render() {
return <button onClick={() => this.setState({ count: this.state.count + 1 })}>+1</button>;
}
}
2:getDerivedStateFromProps
监听 Props 变化间接触发 State 更新(适用于 Props 派生 State 的场景)
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.value !== prevState.value) {
return { value: nextProps.value };
}
return null;
}
1:Redux 监听全局 State
在 Redux 中通过 store.subscribe 监听全局 State 变化:
import store from './store';
class MyComponent extends React.Component {
componentDidMount() {
this.unsubscribe = store.subscribe(() => {
const state = store.getState();
console.log('Redux State 更新:', state);
});
}
componentWillUnmount() {
this.unsubscribe(); // 取消订阅
}
}
1:复杂数据类型监听:
当 State 为对象或数组时,需避免直接修改原数据:
const [user, setUser] = useState({ name: 'Alice', age: 20 });
// 错误写法:直接修改属性不会触发更新
user.age = 21;
// 正确写法:生成新对象
setUser({ ...user, age: 21 });
2:Context API 监听
使用 useContext 结合 useEffect 监听 Context 中的 State 变化
const ThemeContext = React.createContext();
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<ChildComponent />
</ThemeContext.Provider>
);
}
function ChildComponent() {
const { theme } = useContext(ThemeContext);
useEffect(() => {
console.log('主题变化:', theme);
}, [theme]);
}
1:组件内部监听=>useEffect / 生命周期
2:父子组件通信=>回调函数传递
3:全局状态监听=>Redux store.subscribe
4:复杂数据类型=>生成新引用