在某一时段会自动执行的函数
Initialization初始化
constructo()中完成
Mounting 组件第一次挂载到页面的流程
componentWillMount :render之前 组建即将被挂载到页面上时执行
componentDidMount :render之后 组件挂载后执行
Updation 组件更新
shouldComponentUpdate :给出一个布尔值判断是否更新组件
componentWillUpdate :确定更新组件,render前执行
componentDidUpdate :组件更新后,render后执行
componentWillReceiveProps:一般只有子组件会运行,但是在子组件还没挂载时不执行
Unmounting
componentWillUnmount 组件除去挂载后执行
用处
- 父组件更新时子组件也会更新,但有时父组件更新时,子组件不需要更新,为了避免性能浪费,可以使用shouldComponentUpdate,判断子组件属性有没有变化,若没有变化则无需更新
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.content !== this.props.content){
return true;
}
else{
return false;
}
}
- 要使用ajax请求数据时,放在render里会导致循环,因为render是实时更新的,所以把ajax请求放在componentDidMount()里,要使用ajax请求 ,首先在项目目录中,控制台 输入
- yarn add axios 安装 引用后就可以使用
import axios from 'axios'
componentDidMount(){
axios.get('/api/todolist')
.then(()=>{alert('sucess')})
.catch(()=>{alert('fail')})
console.log('Todolist:componentDidMount')
}