react-组件的生命周期

组件生命周期:

命令式编程:jquery(自己寻找要操作的DOM元素,自己写要做的事情)

声明式编程:react(只需要在钩子函数中写东西即可,不需要执行钩子函数)

      这些钩子函数是本身就会执行的,我们重写了一部分,是为了在这个组件的某个时期做一些事情。

生命周期流程:
1. 第一次初始化渲染显示: ReactDOM.render()
  * constructor(): 创建对象初始化 state
  * componentWillMount() : 将要插入回调
  * render() : 用于插入虚拟 DOM 回调
  * componentDidMount() : 已经插入回调
2. 每次更新 state: this.setSate()
  * componentWillUpdate() : 将要更新回调
  * render() : 更新(重新渲染)
  * componentDidUpdate() : 已经更新回调
3. 移除组件: ReactDOM.unmountComponentAtNode(containerDom)
  * componentWillUnmount() : 组件将要被移除回调 
重要的勾子
1) render(): 初始化渲染或更新渲染调用
2) componentDidMount(): 开启监听, 发送 ajax 请求
3) componentWillUnmount(): 做一些收尾工作, 如: 清理定时器
4) componentWillReceiveProps(): 后面需要时讲
代码例子:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>work9</title>
    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/prop-types.js"></script>
    <script src="../js/babel.min.js"></script>
    <script type="text/babel">
        class Life extends React.Component{
            constructor(props){
                super(props)
                //初始化状态
                this.state={
                    opacity:1
                }
                this.distroyComponent=this.distroyComponent.bind(this)
            }
            componentDidMount(){
                //启动循环定时器
                this.intervalId=setInterval(function () {
                    console.log("定时器执行了")
                    let {opacity}=this.state  //这里的this,属于window
                    opacity -= 0.1
                    if(opacity<=0){  //这里的减法有些误差,所以要小于等于0
                        opacity=1
                    }
                    this.setState({opacity})
                }.bind(this),200)
            }
            distroyComponent(){
                ReactDOM.unmountComponentAtNode(document.getElementById("example"))
            }
            componentWillUnmount(){
                //清理定时器
                clearInterval(this.intervalId)
            }
            render(){
                const {opacity}=this.state
                //下面style中:第一个大括号的作用说明里面开始了js代码,第二个大括号代表是style里面的对象;
                return(
                    <div>
                        <h2 style={{opacity:opacity}}>{this.props.msg}</h2>
                        <button onClick={this.distroyComponent}>爱网球</button>
                    </div>
                )
            }
        }
        ReactDOM.render(<Life msg="iwantiwantiwantiwant"/>,document.getElementById("example"))
    </script>
</head>
<body>
<div id="example"></div>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/czh64/p/12102111.html