React生命周期

2019-03-27  本文已影响0人  fb941c99409d

https://www.cnblogs.com/gdsblog/p/7348375.html 写的很好的一篇文章

image
  1. 组件的三个生命周期状态:
* Mount:插入真实 DOM
* Update:被重新渲染
* Unmount:被移出真实 DOM
  1. React 为每个状态都提供了两种勾子(hook)函数,will 函数在进入状态之前调用,did 函数在进入状态之后调用
* componentWillMount()
* componentDidMount() : 已插入真实DOM, 在render之后才会执行
* componentWillUpdate(object nextProps, object nextState)
* componentDidUpdate(object prevProps, object prevState)
* componentWillUnmount()
  1. 生命周期流程:
1. 第一次初始化渲染显示: render()
      * constructor(): 创建对象初始化state
      * componentWillMount() : 将要插入回调
      * render() : 用于插入虚拟DOM回调
      * componentDidMount() : 已经插入回调
2. 每次更新state: this.setSate()
      * componentWillUpdate() : 将要更新回调
      * render() : 更新(重新渲染)
      * componentDidUpdate() : 已经更新回调
3. 删除组件
      * ReactDOM.unmountComponentAtNode(document.getElementById('example')) : 移除组件
      * componentWillUnmount() : 组件将要被移除回调
4. 注意:
     * 一般会在componentDidMount()中: 开启监听, 发送ajax请求
     * 可以在componentWillUnmount()做一些收尾工作: 停止监听
     * componentWillReceiveProps:当props发生变化时执行,初始化render时不执行
class App extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      person:{
        name:'kobe',
        age:18,
      }
    }
    this.num=0;
    console.log('constructor()');
  }
  componentWillMount(){
    console.log('componentWillMount()组件将要被挂载');
    //开定时器更新state
    this.timer=setInterval(()=>{
      this.setState({
        person:{
          name:"mary",
          age:++this.num,
        }
      });
    },100);
  }
  componentDidMount(){
    console.log('componentDidMount()组件挂载完毕');
    //卸载组件
    setTimeout(()=>{
      ReactDOM.unmountComponentAtNode(document.getElementById('example'));
    },4000);
  }
  componentWillUpdate(){
    console.log('componentWillUpdate() 组件将要更新');
  }
  componentDidUpdate(){
    console.log('componentWillUpdate() 组件更新完毕');
  }
  componentWillUnmount(){
    console.log('componentWillUnmount() 组件将要被卸载');
    //组件卸载前 做收尾工作 如 清除定时器
    clearInterval(this.timer);
  }
  render(){
    console.log('render()');
    let {person} = this.state;
    return (
      <div>
          {person.name}---{person.age}
      </div>
    );
  }
}
ReactDOM.render(<App />,document.getElementById('example'));
</script>
上一篇 下一篇

猜你喜欢

热点阅读