react怎么实现数据更新

关于React中数据的更新操作

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

function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
  ReactDOM.render(
    element,
    document.getElementById('root')
  );
}
 
setInterval(tick, 1000);

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

function Clock(props) {
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {props.date.toLocaleTimeString()}.</h2>
    </div>
  );
}
 
function tick() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    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(
            <div>
                <h1>hello world!</h1>
                <h2>It is {this.state.date.toLocaleTimeString()}</h2>
            </div>
        );
    }
}
export default Clock;

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

以上就是react怎么实现数据更新的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » React 答疑