卸载组件
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)
组件挂载流程
- 构造器
- 将要挂载
- render
- 挂载完毕
setState更新流程
forceUpdate流程
父组件render流程
组件的生命周期(旧)
在新版本中除了componentWillUnmount之外,其余都需要加上UNSAFE_
组件的生命周期(新)
新旧生命周期的区别在哪里?
- 在新的生命周期中,废弃了旧版本的3个带will的钩子,新提出了2个钩子。
getDerivedStateFromProps
- 这个函数前面应加static,因为是静态的。
- 通过这个钩子修改的state,state任何时候都取决于props,其他的函数无法进行修改。
- 只要这个钩子拦着,所有的状态都得听props的。
getSnapshotBeforeUpdate与componentDidUpdate协同
getSnapshotBeforeUpdate的使用场景
需求:制作新闻滚动盒子,新渲染的新闻始终在上面,滚动条停在一个位置,这个位置的新闻固定不动展示给用户。
- 首先明确两个概念: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'));
总结:组件的声明周期
- 组件的生命周期,关键还是看懂新的组件生命周期那张图里的流程顺序。