React State

React 里只需要更新组件的state,然后根据新的 state 重新徐娜然用户界面(不要操作DOM)。

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    date: new Date()
   };
   //在state中,定义一条数据 data ,让它为 new Date().该数据不停变化
} render() {
return ( <div> <h1>Hello, world!</h1> <h2>现在时间: {this.state.date.toLocaleTimeString()}.</h2> </div> ); } } ReactDOM.render( <Clock />, document.getElementById('root') );

这个时候,当该组件渲染到页面上后,我们看到这个时候它自己是不会变化的。

这是因为 React 在渲染到 页面上时候,类似单帧页面,只会渲染一次。虽然他的数据在变化,但是我们没有设置让他更新页面数据的操作。所有我们可以通过给this.setState()方法设置一个定时器来更新页面。

componentDidMount() {//React的生命周期方法:页面加载完毕后
    this.timerID = setInterval(
      () => this.tick(),//调用tick函数来修改数据
      1000
    );
  }
componentWillUnmount() {//React的生命周期方法:页面将要销毁时
    clearInterval(this.timerID); 
}
tick() {
  this.setState({ date: new Date() }); //调用this.setState()方法修改数据
}

 总结:

  初始化:this.state = { user : "Premy" };

  初始化可以防止在构造函数  construstor  里;

  修改state : this.setState({ user : "Abc " });

  state  的作用域只属于当前类,不污染其它块。

 

原文地址:https://www.cnblogs.com/mwxz/p/13524290.html