1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| class LifeCycle extends React.Component { constructor(props){ super(props); this.state = { person:{ name:'fuhq', age: 18 } } console.log('constructor()') } // 组件将要被挂载 componentWillMount(){ //console.log(this); console.log('componentWillMount() 组件将要被挂载') // 发送ajax请求, 开启定时器 // 需要手动绑定改变this指向 // setTimeout(function(){ // this.setState({ // person:{ // name:'yanggq', // age: 19 // } // }) // }.bind(this), 1000) // 箭头函数更方便 setTimeout(()=>{ this.setState({ person:{ name:'yanggq', age: 19 } }) }, 2000) } // 组件挂载完毕 componentDidMount(){ console.log('componentDidMount() 组件挂载完毕') // 官方推荐在这个钩子里面发送请求 // 发送ajax请求, 开启定时器 setTimeout(()=>{ // 卸载 ReactDom.unmoutComponentAtNode(document.getElementById('example')) }, 4000)
this.intervalId = setInterval(function(){ console.log('setInterval()') }, 1000) } // 组件将要更新 componentWillUpdate(){ console.log('componentWillUpdate() 组件将要更新') } // 组件更新完毕 componentDidUpdate(){ console.log('componentDidUpdate() 组件更新完毕') } // 组件将要被卸载 componentWillUnmount(){ console.log('componentWillUnmount() 组件将要被卸载') // 做一些收尾工作,关掉定时器 clearInterval(this.intervalId) } render(){ console.log('render()') return ( <div>{person.name}:{person.age}</div> ) } } React.render(<LifeCycle />, document.getElementById('example'));
|