react框架的学习-8-16-2019-生命周期。

海星吧 2019-8-16 3983

上一篇写了如何安装和运行,react组件的结构,并且有生命周期的函数。

这篇来讲一下生命周期比较重要的几个函数。


学过vue的同学就应该知道,生命周期钩子函数就是在组件中默认定义的函数,

而且会根据特定的时间,按照顺序执行。



constructor(props)

一般用来进行初始化操作,比如setState,super(props)


render()

渲染函数,你可以在其中写上html标签

render(){

    return(

        <div>

             <p>hello world</p>

        </div>

    )

}


componentDidMount()

在初始化时只会执行一次,从这个函数开始就能够和其他js框架进行交互了。


componentDidUpdate(props,state)

在组件更新结束后才会执行,初始化render时不执行,

它接受两个参数,一个是props,一个是state


componentWillUnmount()

在组件从界面上移除时执行。它通常做一些网络请求,关闭等工作。



接下来用案例来解释


import React from 'react'


class Timer extends React.Component {

constructor(props) {//初始化

super(props)

this.state = {

date: new Date()//实例化时间函数

}

}

componentDidMount(){//初始化

this.timer = setInterval(()=>{

this.setState({

date:new Date()

})

},1000)//设置时间为一秒

}

componentDidUpdate(props,state){//更新时

console.log(state)//每隔一秒钟就会显示一次时间

}

componentWillUnmount(){//卸载时

clearInterval(this.timer)//取消setInterval设置的 timer

}

render(){

return (

<div>

<h1>{this.state.date.toLocaleTimeString()}</h1>

</div>

)

}

}


export default Timer;




以上组件是一个展示当前时间并且实时更新的功能组件。

在componentDidMount初始化时创建一个时间计时器timer,并且用setInterval函数每隔一秒就调用它。

此时componentDidUpdate函数接受的两个参数中的state收到了更新,用console.log()打印出来,也是每隔一秒就打印一次。

说明页面也是在不断更新中。

而在组件退出时componentWillUnmount函数把计时器关闭。

整个流程就是组件的生命周期。


建议只在componentWillMount,componentDidMount,componentWillReceiveProps方法中可以修改state值


以上取常用的几个生命钩子函数,如果想了解更多,那就点更多。

如果有任何意义上的错误或者你有什么可以补充的知识点欢迎下方留言,

我是海星吧,咱们下一篇见。



弱鸡程序员年底还在加班
最新回复 (1)
  • 欧派兽 2019-8-16
    0 2
    奖励三级精华
    1:管理员给你移区后会显示移到了你之前发帖的区。 2:点击我作为楼主发帖时一楼下的图片签名,可以跳转到站规教程贴。 3:多次水贴水回复会封号哦? 4:不知道回什么的时候就点“里世界专属”,一键随机生成几种回复内容。 5:祝你在里世界玩得愉快!
    • ACG里世界
      3
          
返回
发新帖