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