组件的生命周期可分成三个状态:
Mounting:已插入真实 DOMUpdating:正在被重新渲染Unmounting:已移出真实 DOMApp.jsx中的代码:
<ComponentLife title={this.state.title} updateTitles = {this.updateTitle}/> <button onClick={ this.updateTitle }>父级组件修改title</button>ComponentLife.jsx中的代码:
import React from "react" export default class Component extends React.Component{ constructor(props){ super(props); this.state = { count : 10 } } componentWillMount(){ console.log("componentWillMount"); } componentDidMount(){ console.log("componentDidMount"); } shouldComponentUpdate(){ console.log("shouldComponentUpdate"); return true; } componentWillUpdate(){ console.log("componentWillUpdate"); } componentDidUpdate(){ console.log("componentDidUpdate"); } componentWillReceiveProps(){ console.log("componentWillReceiveProps"); } componentWillUnmount(){ console.log("componentWillUnmount"); } changeHandler = () => { this.setState({ count:this.state.count+=1 }) } updateTitle = () => { this.props.updateTitles(); } render(){ const { count } = this.state; return( <div> react生命周期函数:{count} -- {this.props.title} <button onClick={ this.changeHandler }>修改</button> <button onClick={ this.updateTitle }>子级组件修改title</button> </div> ) } }页面样式: 点击两个修改title的按钮出来的效果都一样,如下: 控制台打印的效果也都一样: