react组件的生存周期

生存周期图

  • 从组件创建到销毁的整个过程
生存周期图.png

完整的生命周期钩子函数

  • 钩子函数就是一个事件,在相应的阶段触发的对应的函数。

创建阶段(mount)

  • constructor:构造函数,这个时候还不算时个组件,只是class自身的初始化
  • getDerivedStateFromProps:检查需要更新的状态
  • render:初始渲染
  • componentDidMount:组件创建完成,并已挂载到DOM上,比较常用
class Cmp extends React.Component{
    constructor(...args){
        super(...args)
        this.state={
            a:1
        }
        console.log('constructor');
    }
    componentDidMount() {
        console.log('创建了')
    }
    render(){
        console.log('渲染了');
        return (
            <div><p>{this.state.a}</p></div>
        )
    }
}
ReactDOM.render(<Cmp></Cmp>,document.getElementById('root'))
// 输出:
// constructor
// 渲染了
// 创建了

更新阶段(updata)

  • getDerivedStateFeomProps:检查组件需要更新的状态
  • shouldComponentUpdate:确定组件是否需要更新,需要使用return值,ture或者false;没有返回值的话会报错;

Warning: Cmp.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.

  • render渲染
  • componentDidUpdate:组件渲染完成
class Cmp extends React.Component{
    constructor(...args){
        super(...args)
        this.state={
            a:1
        }
        console.log('constructor');
    }
    componentDidMount() {
        console.log('创建了')
    }
    componentDidUpdate() {
        console.log('didUpdate')
    }
    shouldComponentUpdate(nextProps, nextState) {
        console.log(nextProps, nextState);
        //这里可以写相关的判断,决定是否进行渲染;
        return true
    }
    
    
    fn(){
        this.setState({
            a:this.state.a +1
        })
    }
    render(){
        console.log('渲染了');
        return (
            <div>
                <p>{this.state.a}</p>
                <input type="button" value="按钮" onClick={this.fn.bind(this)}></input>
            </div>
        )
    }
}
ReactDOM.render(<Cmp></Cmp>,document.getElementById('root'))

结合父子组件、组件传值、componentDidMountcomponentDidUpdateshouldComponentUpdate的应用实例

class Parent extends React.Component{
    constructor(...args){
        super(...args)
        this.state={
            id:1
        }
    }
    fn(){
        this.setState({
            id:this.state.id +1
        })
    }
    render(){
        return (
            <div>
                <p>{this.state.id}</p>
                <input type="button" value="按钮" onClick={this.fn.bind(this)}></input>
                <Child id={this.state.id}></Child>
            </div>
        )
    }
}
class Child extends React.Component{
    constructor(...args){
        super(...args)
        this.state={
            name:'',
            age:''
        }
    }
    componentDidMount() {
        console.log('componentDidMount')
        this.updata(this.props.id)
    }
    componentDidUpdate(prevProps, prevState) {
        console.log('componentDidUpdate')
        if(prevProps.id != this.props.id){
            this.updata(this.props.id)
        }
    }
    
    shouldComponentUpdate(nextProps, nextState) {
        return (nextProps.id != this.props.id || nextState.name != this.state.name)
    }
    updata(id){
        fetch(`../data/data${id}.txt`).then(res=>{
            res.json().then(data=>{
                this.setState({
                    name:data.name,
                    age:data.age
                })
            })
        })
    }
    render(){
        return (
            <div>
                <p>ID:{this.props.id}</p>
                <p>姓名:{this.state.name} 年龄:{this.state.age}</p>
            </div>
        )
    }
}
ReactDOM.render(<Parent></Parent>,document.getElementById('root'))

销毁阶段(Unmount)

  • componentWillUnmount组件销毁的回调函数
class Parent extends React.Component{
    constructor(...args){
        super(...args)
        this.state={
            id:true
        }
    }
    fn(){
        this.setState({
            id:!this.state.id
        })
    }
    render(){
        return (
            <div>
                <p>{this.state.id}</p>
                <input type="button" value="按钮" onClick={this.fn.bind(this)}></input>
                {this.state.id?(<Child></Child>):''}
            </div>
        )
    }
}
class Child extends React.Component{
    constructor(...args){
        super(...args)
    }
    componentDidMount() {
        console.log('didmount')
    }
    componentWillUnmount() {
        console.log('Unmount');
    }
    render(){
        return (
            <div>子组件</div>
        )
    }
}
ReactDOM.render(<Parent></Parent>,document.getElementById('root'))
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。