一、react生命周期介绍
react生命周期全过程:
二、使用方法
1.挂载期
- constructor()构造方法
constructor是ES6对类的默认方法,通过 new命令生成对象实例时自动调用该方法。并且,该方法是类中必须有的,如果没有显示定义,则会默认添加空的constructor( )方法。当存在constructor的时候必须手动调用super方法。在constructor中如果要访问this.props需要传入props
super(props)用来调用基类的构造方法( constructor() ), 也将父组件的props注入给子组件,功子组件读取(组件中props只读不可变,state可变)。
而constructor()用来做一些组件的初始化工作,如定义this.state的初始内容。
代码如下(示例):
class Index extends React.component{
constructor(props){
super(props); // 声明constructor时必须调用super方法
console.log(this.props); // 可以正常访问this.props,因为传入的props
}
}
-
getDerivedStateFromProps(props,state)
getDerivedStateFromProps会在调用render方法之前调用,并且在初始挂在以及后续更新时都会调用,它会返回一个对象来更新state,state的值取决于props
-
render()
当render被调用时,它会检测 this.props 和 this.state的变化,渲染一个虚拟dom
-
componentDidMount()
componentDidMount会在组件挂载后立即执行,此处是实例化请求的好地方,,你可以在componentDidMount()里直接调用setState(),它将触发额外渲染,但此渲染会发生在浏览器更新屏幕之前,既使在render()两次调用的情况下,用户也看不到中间状态,请谨慎使用,因为它会导致性能问题
2.更新期
- getDerivedStateFromProps(props,state)
该方法是挂载期和更新期都会使用到的方法,解释同上
- shouldComponentUpdate(nextProps,nextState)
在渲染之前执行,根据返回值来判断React组件是否受当前state和props更改的影响,state发生变化,默认返回true,组件就会重新渲染。首次渲染或使用forceUpdate()不会调用该方法
- render()
该方法是挂载期和更新期都会使用到的方法,解释同上
- getSnapshotBeforeUpdate(prevProps,prevState)
getSnapshotBeforeUpdate在最近一次渲染输出前执行,此生命周期的任何返回值将作为参数传给componentDidUpdate()。它不是很常见,可能出现在UI处理中
- componentDidUpdate(prevProps,prevState,snapshot)
componentDidUpdate在更新后立即执行,首次渲染不会执行此方法,当组件更新后,可以在此处进行dom操作,当props发生变化时,也可以在此处进行网络请求。。你也可以在componentDidUpdate中直接调用setState(),但是必须包裹在条件语句里,否则会导致死循环
3.卸载期
- componentWillUnmount()
componentWillUnmount会在组件销毁或卸载前执行,此方法中清除定时器,取消网络请求。componentWillUnmount()中不应调用setState(),因为该组件卸载后将不会再重新挂载