react生命周期---componentDidUpdate()

6,667 阅读1分钟

今天在使用websocket更新数据的时候,props变化,但是组件没有重新渲染,最后想到了可以用componentDidUpdate()这个生命周期,好用是好用,但是也出现了一些小问题,首先它只是在更新后才会立即调用,在初始化的时候,是不会调用的,当state或者props改变时触发时,需要做一些条件判断,否则会进入死循环

//大概就是这么个意思
componentDidUpdate(prevProps,prevState){
    if(prevProps!=this.props){
    
    }
}

还需要注意的是,在生命周期如果想使用setState的情况

    无意义使用:componentWillMount,componentWillUnmount;

    有条件使用:componentDidUpdate;

    禁止使用:componentWillUpdate,shouldComponentUpdate;

    正常使用:componentWIllReceiveProps,componentDidMount。
    
componentWillMount和componentWillReceiveProps中,setState会被react内部处理,而不触发render;其他生命周期均正常出发更新渲染。