欢迎莅临我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。
持续学习,不断总结,共同进步,为了踏实,做好当下事儿~
非常期待和您一起在这个小小的网络世界里共同探索、学习和成长。 ✨✨ 欢迎订阅本专栏 ✨✨
The Start点点关注,收藏不迷路
|
React 生命周期与 Hook 是每个 React 开发者必须掌握的核心概念。理解它们的工作原理和适用场景,能帮助开发者编写更高效、可维护的组件代码。本文将深入解析类组件的生命周期方法,对比函数组件中 Hook 的工作机制,并探讨如何合理选择这两种开发模式。
React 类组件的生命周期可以分为三个主要阶段:
class ExampleComponent extends React.Component {
constructor(props) {
super(props); // 挂载阶段开始
this.state = { count: 0 };
}
componentDidMount() {
console.log('组件已挂载');
}
shouldComponentUpdate(nextProps, nextState) {
return nextState.count !== this.state.count; // 更新阶段控制
}
componentDidUpdate() {
console.log('组件已更新');
}
componentWillUnmount() {
console.log('组件即将卸载'); // 卸载阶段
}
render() {
return {this.state.count};
}
}
挂载阶段:组件实例被创建并插入DOM
constructor()
→ render()
→ componentDidMount()
更新阶段:组件因props或state变化而重新渲染
shouldComponentUpdate()
→ render()
→ componentDidUpdate()
卸载阶段:组件从DOM中移除
componentWillUnmount()
componentDidMount:
componentDidMount() {
fetch('/api/data')
.then(res => res.json())
.then(data => this.setState({ data }));
this.timerID = setInterval(() => this.tick(), 1000);
}
shouldComponentUpdate:
shouldComponentUpdate(nextProps, nextState) {
// 仅当count变化时才更新
return nextState.count !== this.state.count;
}
componentWillUnmount:
componentWillUnmount() {
clearInterval(this.timerID);
this.subscription.unsubscribe();
}
React 16.3+ 标记为不安全的生命周期方法:
componentWillMount
→ 使用constructor
或componentDidMount
替代componentWillReceiveProps
→ 使用static getDerivedStateFromProps
componentWillUpdate
→ 使用getSnapshotBeforeUpdate
替代方案示例:
static getDerivedStateFromProps(props, state) {
if (props.value !== state.prevValue) {
return {
prevValue: props.value,
// 其他派生状态...
};
}
return null;
}
类组件存在三大痛点:
this
绑定问题和class的复杂性函数组件的局限性:
function Counter() {
const [count, setCount] = useState(0);
return (
You clicked {count} times
);
}
useEffect(() => {
// 相当于 componentDidMount + componentDidUpdate
document.title = `You clicked ${count} times`;
return () => {
// 相当于 componentWillUnmount
console.log('cleanup');
};
}, [count]); // 仅在count变化时执行
const theme = useContext(ThemeContext); // 上下文访问
const [state, dispatch] = useReducer(reducer, initialState); // 复杂状态管理
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]); // 性能优化
调用规则:
自定义Hook:
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
// 使用:const width = useWindowWidth();
useCallback
缓存函数useMemo
缓存计算结果生命周期方法 | Hook 等效实现 |
---|---|
constructor | useState 初始化 |
componentDidMount | useEffect(() => {}, []) |
componentDidUpdate | useEffect(() => {}, [deps]) |
componentWillUnmount | useEffect 的清理函数 |
shouldComponentUpdate | React.memo + useMemo |
逐步替换示例:
逻辑复用对比:
// HOC方式
const EnhancedComponent = withHOC(BaseComponent);
// Hook方式
function useCustomLogic() {
const [value, setValue] = useState(null);
// ...逻辑
return value;
}
function Component() {
const value = useCustomLogic();
// ...
}
类组件优化:
class OptimizedComponent extends React.PureComponent {
// 自动浅比较props和state
}
函数组件优化:
const MemoizedComponent = React.memo(
function MyComponent(props) {
/* 使用props渲染 */
},
(prevProps, nextProps) => {
/* 自定义比较逻辑 */
}
);
function Parent() {
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
}
核心对比:
适用场景:
学习建议:
未来趋势:
通过深入理解生命周期和Hook的关系,开发者可以更灵活地选择适合场景的开发模式,编写更清晰、更易维护的React代码。
道阻且长,行则将至,让我们一起加油吧!
The Start点点关注,收藏不迷路
|
The Start点点关注,收藏不迷路
|