实现需求:页面上一行文字透明度逐渐减小的动态效果,且透明度到0时又会自动变为1,文字下方有一个按钮,点击按钮删除页面全部元素,如下图所示:
先大致分析下:要想实现动态效果,标签样式中的透明度肯定是动态变化的,可以从组件的状态中取,组件的状态要定时更新,因此需要一个定时器,这个改变组件状态的定时器需要页面渲染完成之后就开始启动;删除按钮则不仅需要删除所有组件,还需要删除上面的定时器。代码如下:
class MyDemo extends React.Component{
state = {opacity:'1'}
componentDidMount() {
this.timeTask = setInterval(() => {
console.log("aaaa");
let opacity = this.state.opacity;
opacity -= 0.1;
if (opacity <= 0) {
opacity = 1;
}
this.setState({opacity:opacity});
}, 200);
}
componentWillUnmount() {
clearInterval(this.timeTask);
}
death = () => {
ReactDOM.unmountComponentAtNode(document.getElementById("test1"));
}
render() {
return (
<div>
<h2 style={{opacity:this.state.opacity}}>React学不会怎么办?</h2>
<button onClick={this.death}>不活了</button>
</div>
)
}
}
ReactDOM.render(<MyDemo/>, document.getElementById("test1"));
以上就用到了两个生命周期函数(也叫钩子):componentDidMount和componentWillUnmount,前者是在组件渲染完毕之后调用的,后者是在组件将要卸载(卸载组件由ReactDom.unmountComponentAtNode方法触发)但还没卸载之前调用的。
React 17之前的生命周期流程图:
自身挂载时:构造器 -> componentWillMount -> render -> componentDidMount
父组件render时(此时一般通过props传承):componentWillReceiveProps -> shouldComponentUpdate -> componentWillUpdate -> render -> componentDidUpdate
调用setState时:setState -> shouldComponentUpdate -> componentWillUpdate -> render -> componentDidUpdate
调用forceUpdate时:forceUpdate -> componentWillUpdate -> render -> componentDidUpdate
上述componentWillReceiveProps方法其实是在组件接受新的props才会调用,即第一次不会调用。shouldComponentUpdate的方法返回true或者false,起着一个阀门的作用,而forceUpdate强制更新,不会经过此阀门。
而React 17以后新的生命周期会计划删除三个生命周期函数:componentWillMount、componentWillReceiveProps、componentWillUpdate,因此不推荐使用。新加了两个生命周期函数:getDerivedStateFromProps和getSnapshotBeforeUpdate,前者是从props中获取/设置状态state,可能会引起歧义,目前也不推荐,后者是在更新之前保存一份快照,即保存更新前的某些状态/参数,以便更新后用。getSnapshotBeforeUpdate在某些特殊场景可能会用到,具体可参考尚硅谷React技术全家桶全套完整版(零基础入门到精通/男神天禹老师亲授)。
总之,无论新版还是旧版的生命周期,最常用的三个钩子函数式:componentDidMount、componentWillUnmount、render。