天天看点

React-17:组件的生命周期总结:组件的声明周期

卸载组件

ReactDOM.unmountComponentAtNode(document.querySelector('.test'));
      

组件挂载完毕

componentDidMount() {
    this.timer = setInterval(() => {
        let {opacity} = this.state;
        opacity = opacity - 0.1;
        if (opacity <= 0) opacity = 1;
        this.setState({opacity:opacity})
    },200)
}
      

循环定时器

this.timer = setInterval(() => {
    let {opacity} = this.state;
    opacity = opacity - 0.1;
    if (opacity <= 0) opacity = 1;
    this.setState({opacity:opacity})
},200)
      

组件挂载流程

  1. 构造器
  2. 将要挂载
  3. render
  4. 挂载完毕
React-17:组件的生命周期总结:组件的声明周期

setState更新流程

React-17:组件的生命周期总结:组件的声明周期

forceUpdate流程

React-17:组件的生命周期总结:组件的声明周期

父组件render流程

React-17:组件的生命周期总结:组件的声明周期

组件的生命周期(旧)

React-17:组件的生命周期总结:组件的声明周期

在新版本中除了componentWillUnmount之外,其余都需要加上UNSAFE_

React-17:组件的生命周期总结:组件的声明周期

组件的生命周期(新)

React-17:组件的生命周期总结:组件的声明周期

新旧生命周期的区别在哪里?

  • 在新的生命周期中,废弃了旧版本的3个带will的钩子,新提出了2个钩子。

https://link.juejin.cn?target= getDerivedStateFromProps

  • 这个函数前面应加static,因为是静态的。
  • 通过这个钩子修改的state,state任何时候都取决于props,其他的函数无法进行修改。
  • 只要这个钩子拦着,所有的状态都得听props的。

https://link.juejin.cn?target= getSnapshotBeforeUpdate与componentDidUpdate协同

React-17:组件的生命周期总结:组件的声明周期

getSnapshotBeforeUpdate的使用场景

https://link.juejin.cn?target= 需求:制作新闻滚动盒子,新渲染的新闻始终在上面,滚动条停在一个位置,这个位置的新闻固定不动展示给用户。

  • 首先明确两个概念:scroolHeight指的是当前滚动盒子的总高度,scrollTop指的是从盒子的最底部出发,向上跳多少高度。
class NewsList extends React.Component {
    state = { newsArr: [] };

    componentDidMount() {
        setInterval(() => {
            const { newsArr } = this.state;
            const news = "新闻" + (newsArr.length + 1);
            this.setState({ newsArr: [news, ...newsArr] });
        }, 900)
    }
    getSnapshotBeforeUpdate() {
        // 返回当前list盒子的高度
        return this.refs.list.scrollHeight;
    }
    componentDidUpdate(preProps,preState,height) {
        this.refs.list.scrollTop += this.refs.list.scrollHeight - height;
    }
    render() {
        return (
            <div className="list" ref="list">
                {
                    this.state.newsArr.map((value,index) => {
                        return (
                            <div key={index} className="news">{value}</div>
                        )
                    })
                }
            </div>
        )
    }
}
ReactDOM.render(<NewsList />, document.querySelector('.test'));
      

总结:组件的声明周期

  • 组件的生命周期,关键还是看懂新的组件生命周期那张图里的流程顺序。

继续阅读