React学习:State 和 生命周期的应用

React :元素构成组件,组件又构成应用。
React核心思想是组件化,其中 组件 通过属性(props) 和 状态(state)传递数据。

首先看个实例

写法一:函数式组件

function Clocks(props){
  return <div>time is : {props.date.toLocaleTimeString()}</div>;
}
function trick(){
  let clockElement =  <Clocks date = {new Date()}/>;//clockElement必须放trick里
  ReactDOM.render(
    clockElement,
    document.getElementById('root')
  );
}
setInterval(trick,1000);

写法二:类组件(一般都用这个)

class Clocks extends React.Component{
  render(){
    return <div>time is : {this.props.date.toLocaleTimeString()}</div>
  }
}

function trick(){
  let clockElement =  <Clocks date = {new Date()}/>;//clockElement必须放trick里
  ReactDOM.render(
    clockElement,
    document.getElementById('root')
  );
}
setInterval(trick,1000);

输出(每秒更新一回):
这里写图片描述

在上面中加入 状态 和 生命周期

class Clocks extends React.Component{
  // 类 构造函数 初始化 this.state
  constructor(props){
    super(props);//如果不加这句,this.props 将在 constructor(构造函数) 中是 undefined(未定义)
    this.state = {date:new Date()};
  }
  //挂载:第一次渲染render 到DOM后,调用它
  componentDidMount(){
    this.timerId = setInterval(
      () => this.tick(),
      1000
    );
  }
  //卸载:产生的 DOM 被销毁时,调用它
  componentWillUnmount(){
    clearInterval(this.timerId);
  }
  tick(){
    this.setState({
      date:new Date()
    });
  }
  render(){
    return (
      <div>
        time is : {this.state.date.toLocaleTimeString()}
      </div>
    );
  }
}

ReactDOM.render(
  <Clocks/>,
  document.getElementById('root')
);

输出:同上

上面调用方法的顺序:
(1)当 < Clock /> 被传入 ReactDOM.render() 时, React 会调用 Clock组件的构造函数。 因为 Clock 要显示的是当前时间,所以它将使用包含当前时间的对象来初始化 this.state 。

(2)然后 React 调用了 Clock 组件的 render() 方法。 React 从该方法返回内容中得到要显示在屏幕上的内容。然后,React 然后更新 DOM 以匹配 Clock 的渲染输出。

(3)当 Clock 输出被插入到 DOM 中时,React 调用 componentDidMount() 生命周期钩子。在该方法中,Clock 组件请求浏览器设置一个定时器来一次调用 tick()。

(4)浏览器会每隔一秒调用一次 tick()方法。在该方法中, Clock 组件通过 setState() 方法并传递一个包含当前时间的对象来安排一个 UI 的更新。
通过 setState(), React 得知了组件 state(状态)的变化, 随即再次调用 render() 方法,获取了当前应该显示的内容。 这次,render() 方法中的 this.state.date 的值已经发生了改变, 从而,其输出的内容也随之改变。React 于是据此对 DOM 进行更新。

(5)如果通过其他操作将 Clock 组件从 DOM 中移除了, React 会调用 componentWillUnmount() 生命周期钩子, 所以计时器也会被停止。

猜你喜欢

转载自blog.csdn.net/b954960630/article/details/79849989