关于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中文网!