
关注让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言问题:请你简要介绍一下React的生命周期。 回答: React组件有若干个生命周期函数,在不同的时刻会自动调用执行,并允许我们在合适的时机添加一些自定义的代码,用于实现更加复杂的功能。 React生命周期可分为三个阶段:挂载阶段、更新阶段和卸载阶段。 一、挂载阶段
import React, {Component} from 'react';
export default class Lifecycle extends Component {
constructor(props) {
super(props);
console.log('constructor');
this.state = {
count: 0
}
}
// 在 v16.3 之前可以使用
// componentWillMount() {
// console.log('componentWillMount(挂载前)');
// }
static getDerivedStateFromProps(props, state) {
console.log('getDerivedStateFromProps(挂载前/更新时)');
return null;
}
componentDidMount() {
console.log('componentDidMount(挂载后)');
}
shouldComponentUpdate(nextProps, nextState) {
console.log('shouldComponentUpdate(更新前)');
return true
}
// 在 v16.3 之前可以使用
// componentWillUpdate(nextProps, nextState) {
// console.log('componentWillUpdate(更新前)');
// }
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('componentDidUpdate(更新后)');
}
componentWillUnmount() {
console.log('componentWillUnmount(卸载后)');
}
handleClick = () => {
this.setState({
count: this.state.count + 1
});
}
render() {
console.log('render(渲染)');
return (
<div>
<h2>React生命周期</h2>
<button onClick={this.handleClick}>点击</button>
</div>
);
}
}
以上就是React生命周期的详细介绍和一个案例,希望对你有所帮助。