React State(状态)简单演示

添加一个类构造函数来初始化状态 this.state,类组件应始终使用 props 调用基础构造函数

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

class Clock extends React.Component{
  constructor(props){
    super(props);
    this.state={
      time:new Date()
    }
  }

  render(){
    return(
      <div>{this.state.time.toLocaleTimeString()}</div>
    )
  }
}

  ReactDOM.render(
    <div>
      <Clock/>
    </div>,
    document.getElementById('example')
  );

serviceWorker.unregister();

将生命周期方法添加到类中
每当 Clock 组件第一次加载到 DOM 中的时候,我们都想生成定时器,这在 React 中被称为挂载。
同样,每当 Clock 生成的这个 DOM 被移除的时候,我们也会想要清除定时器,这在 React 中被称为卸载。

componentDidMount() 与 componentWillUnmount() 方法被称作生命周期钩子。
在组件输出到 DOM 后会执行 componentDidMount() 钩子,我们就可以在这个钩子上设置一个定时器。
this.timerID 为定时器的 ID,我们可以在 componentWillUnmount() 钩子中卸载定时器。

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

class Clock extends React.Component{
  constructor(props){
    super(props);
    this.state={
      time:new Date()
    }
  }

  //当 Clock 的输出插入到 DOM 中时
  componentDidMount(){
    this.timer=setInterval(()=>{
      this.tick()
    },1000);
  }

  //Clock 组件被从 DOM 中移除
  componentWillUnmount(){
    clearInterval(this.timer)
  }

  tick(){
    this.setState({
      time:new Date()
    })
  }

  render(){
    return(
      <div>{this.state.time.toLocaleTimeString()}</div>
    )
  }
}

  ReactDOM.render(
    <div>
      <Clock/>
    </div>,
    document.getElementById('example')
  );

serviceWorker.unregister();

数据自顶向下流动/单向数据流

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

function DateFormat(props){
  return(
    props.date.toLocaleTimeString()
  )
}

class Clock extends React.Component{
  constructor(props){
    super(props);
    this.state={
      time:new Date()
    }
  }

  //当 Clock 的输出插入到 DOM 中时
  componentDidMount(){
    this.timer=setInterval(()=>{
      this.tick()
    },1000);
  }

  //Clock 组件被从 DOM 中移除
  componentWillUnmount(){
    clearInterval(this.timer)
  }

  tick(){
    this.setState({
      time:new Date()
    })
  }

  render(){
    return(
      <DateFormat date={this.state.time}/>
    )
  }
}

  ReactDOM.render(
    <div>
      <Clock/>
    </div>,
    document.getElementById('example')
  );

serviceWorker.unregister();

为了表明所有组件都是真正隔离的,我们可以创建一个 App 组件,它渲染三个Clock

 

原文地址:https://www.cnblogs.com/chenyingying0/p/12690923.html