如何用HTML记录更新数据,react怎么实现数据更新

9d2b86e361620427b6e990fc70e5f032.png

关于React中数据的更新操作

关于数据更新操作,如果首次接触React的话,我们可能会想到给将更新的数据写到定时器中,让数据不断改变,像这样做:function tick() {

const element = (

Hello, world!

It is {new Date().toLocaleTimeString()}.

);

ReactDOM.render(

element,

document.getElementById('root')

);

}

setInterval(tick, 1000);

这样做,没有将时间封装出来,即不能重用。下面我们将时间封装成一个clock类。function Clock(props) {

return (

Hello, world!

It is {props.date.toLocaleTimeString()}.

);

}

function tick() {

ReactDOM.render(

,

document.getElementById('root')

);

}

setInterval(tick, 1000);

我们又会发现,我们每次都要new Date()传入给Clock的date属性。也就是所Clock的改变不是由自身决定的,此时我们可能会想到类,类的状态是私有的。import React,{Component} from "react";

class Clock extends React.Component{

//Clock构造函数

constructor(props){

super(props);

this.state={

date:new Date()

};

}

//插入DOM前的回调函数

componentDidMount() {

this.timerID=setInterval(()=>{

this.tick()

},1000)

}

//组件销毁前的回调

componentWillUnmount(){

clearInterval(this.timerID);

}

tick() {

this.setState({

date:new Date()

});

}

render(){

return(

hello world!

It is {this.state.date.toLocaleTimeString()}

);

}

}

export default Clock;

更多相关技术文章,请访问HTML中文网!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值