4-8、React中的生命周期函數(shù)

生命周期函數(shù)指某一個時刻組件會自動調(diào)用執(zhí)行的函數(shù)
1)初始化(initialization)
初始化props and state中數(shù)據(jù)
2)掛載時(Mounting)
// 在組件即將被掛載到頁面的時刻自動執(zhí)行
componentWillMount() {
console.log('componentWillmount')
}
render () {
console.log('render')
}
// 在組件被掛載到頁面之后,自動執(zhí)行
componentDidMount() {
console.log('componentDidmount')
}
3)更新時(Updation)
// 在組件更新之前,它會自動被執(zhí)行
shouldComponentUpdate() {
console.log('shouldComponentUpdate')
return true
}
//組件被更新之前, 它會自動執(zhí)行,但是它在shouldComponentUpdate之后被執(zhí)行
// 如果shouldComponentUpdate返回true它才執(zhí)行
// 如果返回false,這個函數(shù)就不會執(zhí)行了
componentWillUpdate () {
console.log('componentWillUpdate')
}
// 組件更新完成之后會被執(zhí)行
componentDidUpdate () {
console.log('componentDidUpdate')
}
componentWillReceiveProps
//子組件中
// 1. 當(dāng)一個組件從父組件接收參數(shù)
// 2. 如果這個組件第一次存在于父組件中,不會被執(zhí)行
// 3. 如果這個組件之前已經(jīng)存在于父組件中,才會執(zhí)行
// 4. 滿足2,3情況下只要父組件的render函數(shù)被重新執(zhí)行了,子組件的這個生命周期函數(shù)就會被執(zhí)行
componentWillReceiveProps() {
console.log('child componentWillReceiveProps')
}
4)組件卸載時(Unmounting)
//子組件中
// 當(dāng)這個組件即將被從頁面中剔除的時候會執(zhí)行
componentWillUnmount () {
console.log('componentWillUnmount')
}
4-9、React生命周期的使用場景
避免子組件的重復(fù)執(zhí)行
shouldComponentUpdate (nextProps,nextState) {
if(nextProps.content !== this.props.content){
return true
} else{
return false
}
}
// 發(fā)送ajax請求數(shù)據(jù)
componentWillMount() {
// console.log('componentWillmount')
axios.get('/api/test').then(() => {
console.log('axios get')
}).catch((error) => {
console.log('error',error)
})
}
4-10、使用Charles實現(xiàn)本地數(shù)據(jù)mock
Charles——中間代理服務(wù)器
- 高版本Charles不支持localhost代理,需要添加localhost.charlesproxy.com才能訪問,具體可參考https://blog.csdn.net/qq_41833434/article/details/88873940這篇文章