为了账号安全,请及时绑定邮箱和手机立即绑定

为什么 render 里的 log 被调用两次?

import React from 'react'


class Clock extends React.Component {

 constructor(props){

   super(props)

   this.state = {

     time: new Date()

   }

 }

 //生命周期函数 组件创建完成

 componentDidMount(){

   //创建定时器,间隔 1s

   this.timer = setInterval(() => {

     this.setState({

       time: new Date()

     })

   }, 1000);

 }

 //生命周期函数 组件更新

 componentDidUpdate(currentProps,currentState){

    console.log(currentState);

 }

 //生命周期函数 组件即将销毁

 componentWillUnmount(){

   clearInterval(this.timer)

 }

 render(){

    console.log('---render---'); //调用两次

   

   return (

     <div>

       <h2 >电子时钟</h2>

       <br></br>

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

     </div>

   )

 }

}

export default Clock;


正在回答

1 回答

每次state数据更新,都会重新走render方法重新渲染,然后通过diff算法只更新有数据更新的地方。

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

为什么 render 里的 log 被调用两次?

我要回答 关注问题
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号