React之路-State & 生命周期

405 阅读2分钟

改装之前的计时器案例

function Clock(props){
  return(
    <div>
      <h2>当前时间 {new Date().toLocaleTimeString()}</h2>
    </div>
  );
}

function getTime() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('root')
  )
}

setInterval(getTime, 1000);

我们希望只编写一次代码,便可以让 Clock 组件自我更新,所以需要使用state, state 是私有,并且完全受控于当前组件

使用state实现组件的自我更新

修改函数组件成class组件

class Clock extends React.Component {
    render(){
      return(
        <div>
          <h2>当前时间 {this.props.date.toLocaleTimeString()}</h2>
        </div>
      )
    }
}

//新建Clock class继承React.Compant
//新建一个render函数
//将函数组件返回的react对象迁移到新的render函数中
//将使用props的位置修改成this.props

在组件内部使用局部的state

1.把 render() 方法中的 this.props.date 替换成 this.state.date

class Clock extends React.Component {
    render(){
      return(
        <div>
          <h2>当前时间 {this.state.date.toLocaleTimeString()}</h2>
        </div>
      )
    }
}

2.添加一个 class 构造函数,然后在该函数中为 this.state 赋初值

class Clock extends React.Component {
  constructor(props){
    super(props);
    this.state = {date:new Date()};
  }
    render(){
      return(
        <div>
          <h2>当前时间 {this.state.date.toLocaleTimeString()}</h2>
        </div>
      )
    }
}

3.移除 元素中的 date 属性

function getTime() {
  ReactDOM.render(
    <Clock />,
    document.getElementById('root')
  )
}

使用生命周期

//挂载componentDidMount
//卸载componentWillUnmount
class Clock extends React.Component {
  constructor(props){
    super(props);
    this.state = {date:new Date()};
  }
  // 挂载
  componentDidMount() {
    this.timeId = setInterval(
      () =>this.getTime(),1000
    )
  }
  // 卸载
  componentWillUnmount() {
    clearInterval(this.timeId)
  }
  getTime() {
    this.setState({
      date: new Date()
    });
  }
  render(){
    return(
      <div>
        <h2>当前时间 {this.state.date.toLocaleTimeString()}</h2>
      </div>
    )
  }
}
ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

//在执行ReactDOM.render时,会加载Clock组件
//组件执行会先加载构造函数,初始化this.state
//再去执行组件中的render函数更新展示DOM渲染输出
//在组件被挂载到页面的时候会执行componentDidMount挂载的声明周期函数,每一秒执行一次getTime()
//Clock组件会通过setState方法更新,React通过重新调用render函数,渲染出新的数据
//在页面卸载是的时候执行componentWillUnmount卸载的声明周期函数

如何修改state

需要使用this.setState来修改,不可以直接使用this.state来修改

构造函数是唯一可以给 this.state 赋值的地方

constructor(props){
    super(props);
    this.state = {date:new Date()};
  }

State 的更新可能是异步的

setState()接收一个函数而不是对象

this.setState((state, props) => ({
  counter: state.counter + props.increment
}));

State 的更新会被合并

当state中包含多个独立的变量的时候,可以单独的对变量进行更新