react生命周期(类组件/函数组件)
React组件的生命周期可以分为三个阶段:
- 初始化阶段:当组件实例被创建并挂载到DOM中时,会执行这些生命周期方法。
- 更新阶段:当组件的props或state发生变化时,会执行这些生命周期方法。
- 卸载阶段:当组件从DOM中卸载时,会执行这些生命周期方法。
类组件的生命周期方法:
- constructor(props)
- static getDerivedStateFromProps(props, state)
- render()
- componentDidMount()
- shouldComponentUpdate(nextProps, nextState)
- getSnapshotBeforeUpdate(prevProps, prevState)
- componentDidUpdate(prevProps, prevState, snapshot)
- componentWillUnmount()
- componentDidCatch(error, info) (错误边界)
函数组件的钩子:
- useState()
- useEffect(() => { ... }, [dependencies])
- useContext()
- useReducer()
- useCallback()
- useMemo()
- useRef()
代码示例:
类组件:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
}
componentDidMount() {
document.title = `You clicked ${this.state.counter} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.counter} times`;
}
render() {
return (
<div>
<p>You clicked {this.state.counter} times</p>
<button onClick={() => this.setState({ counter: this.state.counter + 1 })}>
Click me
</button>
</div>
);
}
}
函数组件(使用hooks):
function MyComponent() {
const [counter, setCounter] = useState(0);
useEffect(() => {
document.title = `You clicked ${counter} times`;
});
return (
<div>
<p>You clicked {counter} times</p>
<button onClick={() => setCounter(counter + 1)}>Click me</button>
</div>
);
}
评论已关闭