好客租房62-組件的生命周期三個階段-4卸載時
- 2022 年 5 月 21 日
- 筆記
- 歌謠-React-好客租房筆記
執行時機
//導入react
import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
//導入組件
// 約定1:類組件必須以大寫字母開頭
// 約定2:類組件應該繼承react.component父類 從中可以使用父類的方法和屬性
// 約定3:組件必須提供render方法
// 約定4:render方法必須有返回值
class App extends React.Component{
constructor(props){
super(props)
console.log('生命周期鉤子函數:construtor')
this.state={
count:0
}
}
//初始化state
//1進行dom操作
//2發送網路請求
componentDidMount(){
const title=document.getElementById("title")
console.log(title,"title")
console.log('生命周期鉤子函數:componentDidMount')
}
handleClick=()=>{
this.setState({
count:this.state.count+1
})
}
render(){
console.log('生命周期鉤子函數:render')
return (
<div id='title'>
<Counter count={this.state.count}></Counter>
<button id='btn' onClick={this.handleClick}>打豆豆</button>
</div>
)
}
}
class Counter extends React.Component{
render(){
console.log('子組件生命周期鉤子函數:render')
return <h1>統計豆豆被打的次數:{this.props.count}</h1>
}
componentDidUpdate(prevProps){
console.log('子組件生命周期鉤子函數-生命周期函數-:componentDidUpdate')
const title=document.getElementById("title")
console.log(title,"titleChild")
console.log("上一次的props",prevProps,"當前的prps",this.props)
}
componentWillUnmount(){
console.log("生命周期鉤子函數銷毀函數")
}
}
ReactDOM.render(<App></App>, document.getElementById('root'))