生命周期
生命周期:指对象从创建,到销毁的过程,就是一个生命周期 钩子函数:在某时某刻自动被调用的函数就是钩子函数
-
挂载期
//构造函数. 作用: 在初始化时做state 数据的赋值工作 constructor(props){ super(props) console.log('==constructor=='); // console.log(this.props); this.state = { name:'贾玲' } } //从props中获取stats数据 static getDerivedStateFromProps(props,state){ console.log('==getDerivedStateFromProps=='); // 必须return 一个对象或者null console.log(props); console.log(state); return state } //作用:做jsx模板的解析, render() { console.log('==render=='); //报错 // console.log(document.querySelector('h1').innerHTML); const {age} = this.props return ( <div className="alert alert-info"> <h1>生命周期</h1> <div>age:{age}</div> </div> ) } //作用: 定时器 延时器 轮播图 等等各种请求 componentDidMount(){ console.log('==componentDidMount=='); console.log(document.querySelector('h1').innerHTML);= }
-
更新期:当props或着state的数据发生改变的时候,处于更新期
// getDerivedStateFromProps //应该更新组件吗? /** * 必须return一个结果 如果是true,表示更新数据 如果是false表示不更数据 * 应用:在实际开发中,有一些特殊的业务逻辑在更新完数据之后不希望用户看到,这是该钩子函数就可以实现 */ shouldComponentUpdate(){ console.log('==shouldComponentUpdate=='); return true } // render... // 组件更新完成 componentDidUpdate(prevProps,prevState){ console.log('==componentDidUpdate=='); //获取的是更新之前的props console.log(prevProps); // 获取更新之前的state console.log(prevState); }