4-8、React中的生命周期函数
![](https://img.haomeiwen.com/i6793907/3738be5b0eb32b01.png)
生命周期函数指某一个时刻组件会自动调用执行的函数
1)初始化(initialization)
初始化props and state中数据
2)挂载时(Mounting)
// 在组件即将被挂载到页面的时刻自动执行
componentWillMount() {
console.log('componentWillmount')
}
render () {
console.log('render')
}
// 在组件被挂载到页面之后,自动执行
componentDidMount() {
console.log('componentDidmount')
}
3)更新时(Updation)
// 在组件更新之前,它会自动被执行
shouldComponentUpdate() {
console.log('shouldComponentUpdate')
return true
}
//组件被更新之前, 它会自动执行,但是它在shouldComponentUpdate之后被执行
// 如果shouldComponentUpdate返回true它才执行
// 如果返回false,这个函数就不会执行了
componentWillUpdate () {
console.log('componentWillUpdate')
}
// 组件更新完成之后会被执行
componentDidUpdate () {
console.log('componentDidUpdate')
}
componentWillReceiveProps
//子组件中
// 1. 当一个组件从父组件接收参数
// 2. 如果这个组件第一次存在于父组件中,不会被执行
// 3. 如果这个组件之前已经存在于父组件中,才会执行
// 4. 满足2,3情况下只要父组件的render函数被重新执行了,子组件的这个生命周期函数就会被执行
componentWillReceiveProps() {
console.log('child componentWillReceiveProps')
}
4)组件卸载时(Unmounting)
//子组件中
// 当这个组件即将被从页面中剔除的时候会执行
componentWillUnmount () {
console.log('componentWillUnmount')
}
4-9、React生命周期的使用场景
避免子组件的重复执行
shouldComponentUpdate (nextProps,nextState) {
if(nextProps.content !== this.props.content){
return true
} else{
return false
}
}
// 发送ajax请求数据
componentWillMount() {
// console.log('componentWillmount')
axios.get('/api/test').then(() => {
console.log('axios get')
}).catch((error) => {
console.log('error',error)
})
}
4-10、使用Charles实现本地数据mock
Charles——中间代理服务器
- 高版本Charles不支持localhost代理,需要添加localhost.charlesproxy.com才能访问,具体可参考https://blog.csdn.net/qq_41833434/article/details/88873940这篇文章
网友评论