react 的生命周期

2018-05-30  本文已影响0人  中二少爷

//constructor 参数有两个 props context 可以获取到父组件传下来的props context 一定要写super()函数

  constructor(props) {

    // 只要组件存在 constructor 就必须要写super 否则this指向会错误

    super(props);

    this.state = {

      val: ''

    };

  }


//组件将要挂在执行

// 一般使用在服务器渲染的时候使用

//不推荐这里请求 ajax  如果数据是空的  页面空白

  componentWillMount() {

    console.log(1)

  }


//组件渲染完成

// 组件第一次渲染完成 此时dom 已经生成 可以在这里请求ajax 返回数据  setState() 组件会重新渲染

  componentDidMount() {

    console.log(2)

  }



//接受到父组件的props 需要重新渲染组价的时候用的比较多

  componentWillReceiveProps (nextProps) {

  }



// 唯一 用于控制组件重新渲染生命周期的  return false 阻止组件更新

  // shouldComponentUpdate(nextProps,nextState) {

  //    //return false

  // }



// 返回true 以后,组件进入重新渲染的流程

  componentWillUpdate (nextProps,nextState) {

  }

// 在组件更新完数据  会进入这个函数  作用是拿到更新之前的 props和state

  componentDidUpdate(prevProps,prevState) {

  }

// 经常会用到的一个生命周期 

//1. 清除定时器  setTimeout setInterval

//2. 移除所有组件中的监听 removeEventListener

//3. 也许你会经常 遇到这个warning 

  componentWillUnmount (){

  }


react this 指向问题

  // 1 react 的this 指向问题 解决方案 箭头函数 ()=》 this.onclick()

  // 2 this.inclick = this.inclick.bind(this)

  // 3  this.inclick.bind(this)




//render 函数会插入 jsx 生成dom结构 react会生成一份虚拟的dom树

  render() {

上一篇 下一篇

猜你喜欢

热点阅读