React Component,就像人会有生老病死一样有生命周期。一般而言 Component 有以下三种生命周期的状态:
Mounting:已插入真实的 DOM
Updating:正在被重新渲染
Unmounting:已移出真实的 DOM
针对 Component 的生命周期状态 React 也有提供对应的处理方法:
Mounting
componentWillMount()
componentDidMount()
Updating
componentWillReceiveProps(object nextProps):已载入组件收到新的参数时呼叫
shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时呼叫,起始不会呼叫除非呼叫 forceUpdate()
componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)
Unmounting
componentWillUnmount()
很多读者一开始学习 Component 生命周期时会觉得很抽象,所以接下来用一个简单范例让大家感受一下 Component 的生命周期。读者可以发现当一开始载入组件时第一个会触发 console.log('constructor');,依序执行 componentWillMount、componentDidMount ,而当点击文字触发 handleClick() 更新 state 时则会依序执行 componentWillUpdate、componentDidUpdate:
class MyComponent extends React.Component { constructor(props) { super(props); console.log('constructor'); this.handleClick = this.handleClick.bind(this); this.state = { name: 'Mark', } } handleClick() { this.setState({'name': 'Zuck'}); } componentWillMount() { console.log('componentWillMount'); } componentDidMount() { console.log('componentDidMount'); } componentWillReceiveProps() { console.log('componentWillReceiveProps'); } componentWillUpdate() { console.log('componentWillUpdate'); } componentDidUpdate() { console.log('componentDidUpdate'); } componentWillUnmount() { console.log('componentWillUnmount'); } render() { return ( <div onClick={this.handleClick}>Hi, {this.state.name}</div> ); } } ReactDOM.render(<MyComponent />, document.getElementById('app'));
下面是一张React组件生命周期的流程图整理图:
作者:X北辰北
链接:https://xuqwblog.blog.csdn.net/article/details/91039620
来源:CSDN
著作权归作者所有,转载请联系作者获得授权,切勿私自转载。