1. 程式人生 > 實用技巧 >REACT--react生命週期(舊)

REACT--react生命週期(舊)

 /*
  1.初始化階段:由ReactDOM.render()觸發(初次渲染的時候)
   1.construtor()
   2.conponentWillMount()
   3.render()
   4.componentDidMount()
  2.由元件內部this.setState()或父元件render觸發
   1.shouldComponentUpdate()
   2.componentWillUpdate()
   3.render()
   4.compontentDidUpdate()
  3.解除安裝元件:由ReactDOM.unmountConponentAtNode()觸發
   1.componentWillUnmount() 

  */
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <title>Document</title>
 8     <script src="https://unpkg.com/react@16/umd/react.development.js"
crossorigin></script> 9 10 <!-- 該檔案向外暴露了一個物件 React-Dom --> 11 <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> 12 <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> 13 <script src="https://unpkg.com/[email protected]/prop-types.js"
></script> 14 15 </head> 16 17 <body> 18 19 <div id="app"></div> 20 <script type="text/babel"> 21 class Father extends React.Component{ 22 constructor(props){ 23 super(props) 24 console.log('constructor') 25 } 26 state = { relation:'爸爸'}; 27 render(){ 28 return( 29 <div> 30 <h1>{this.state.relation}</h1> 31 <button onClick={this.changeRelation} >修改關係</button> 32 <button onClick = {this.destoryComponent}>銷燬元件</button> 33 <Son relation={this.state.relation} /> 34 </div> 35 ) 36 } 37 destoryComponent = () =>{ 38 ReactDOM.unmountComponentAtNode(document.getElementById("app")) 39 } 40 componentWillMount(){ 41 console.log("componentWillMount") 42 } 43 componentDidMount(){ 44 console.log("componentDidMount") 45 } 46 shouldComponentUpdate(){ 47 console.log("shouldComponentUpdate") 48 return true; 49 } 50 componentWillUpdate(){ 51 console.log("componentWillUpdate") 52 } 53 componentDidUpdate(){ 54 console.log("componentDidUpdate") 55 } 56 componentWillUnmount(){ 57 console.log("componentWillUnmount") 58 } 59 changeRelation = ()=>{ 60 const {relation} = this.state 61 this.setState({relation:"兒子"}) 62 } 63 } 64 class Son extends React.Component{ 65 render(){ 66 return( 67 <div> 68 <h1>我是你:{this.props.relation}</h1> 69 </div> 70 ) 71 } 72 componentWillReceiveProps(){ 73 console.log("componentWillReceiveProps") 74 } 75 } 76 ReactDOM.render(<Father />,document.getElementById("app")) 77 </script> 78 </body> 79 80 </html>