react组件的生命周期
总览
React的生命周期大体可以分为三个部分,一,挂载阶段;二更新阶段三,卸载阶段
挂载时
-
constructor:接收两个参数props,context;注意:使用construct时必须把props作为参数传给super,不然this指向会发生错误。
-
getDerivedStateFromProps(nextProps,state):
-
返回值:返回一个对象来更新state,如果时null则不更新;
-
参数:第一个是最新的props,第二个是之前的state;
-
getDerivedStateFromProps是一个静态函数,也就是在getDerivedStateFromProps无法访问到this,而应该用nextProps和state来进行判断。
-
是react16.4版本的更新。
-
static getDerivedStateFromProps(nextProps, prevState) { const {type} = nextProps; // 当传入的type发生变化的时候,更新state if (type !== prevState.type) { return { type, }; } // 否则,对于state不进行任何操作 return null; }
-
-
render( ) :在挂载和更新时都会使用到render函数。
-
componentDidMounted ( ):可以在这里获取dom元素操作页面和发送AJAX请求。可以加上async。里面有setState函数时不会再进入该生命周期
更新时
state或者props发生改变时:
-
getDerivedStateFromProps(nextProps,state)
-
shouldComponentUpdate(nextProps,nextState):
-
作用:主要用于性能优化,唯一控制组件重新渲染的生命周期;可以通过return false来阻止组件的更新,return true继续进入生命周期中。
-
使用:nextProps和nextState可以获得最新的props和state,而this.props和this.state可以获得当前的props和state,可以通过比较这二者决定是否相同,然后来决定是否跳过。
-
代码:
shouldComponentUpdate(nextProps, nextState) { if (this.props.color !== nextProps.color) { //判断color是否改变 return true; } if (this.state.count !== nextState.count) { //判断count是否改变 return true; } return false; //如果两个都不改变,则不重新渲染 }
-
-
render
-
getSnapshotBeforeUpdate:
-
作用:在方法在最近一次渲染输出(提交到 DOM 节点)之前调用,我们可以访问更新前的 props 和 state。
-
注意:getSnapshotBeforeUpdate() 方法需要与 componentDidUpdate() 方法一起使用,否则会出现错误。
-
代码:
class Header extends React.Component { constructor(props) { super(props); this.state = {favoritesite: "runoob"}; } componentDidMount() { setTimeout(() => { this.setState({favoritesite: "google"}) }, 1000) } getSnapshotBeforeUpdate(prevProps, prevState) { document.getElementById("div1").innerHTML = "在更新前喜欢的网站是:" + prevState.favoritesite; } componentDidUpdate() { document.getElementById("div2").innerHTML = "更新后喜欢的网站是:" + this.state.favoritesite; } render() { return ( <div> <h1>我喜欢的网站是 {this.state.favoritesite}</h1> <div id="div1"></div> <div id="div2"></div> </div> ); } } ReactDOM.render(<Header />, document.getElementById('root'));
-
-
componentDidUpdate:注意:每当setState改变数据时都会重新进入该生命周期,所以不要在这里面写setState函数,不然会发生死循环。
forceUpdate时
不会经过shouldComponentUpdate阶段
卸载时
- componentWillUnmount:可以在此清除定时器,鼠标移动事件等。
被移除的生命周期
- componentWillMount ——>UNSAFE_componentWillMount
- componentWillReceiveProps ——>UNSAFE_componentWillReceiveProps
- componentWillUpdate——>UNSAFE_componentWillUpdate
移除并不代表不能使用,实际上在生命周期前面添加上**UNSAFE_**即可。