赞
踩
react 生命周期指的是组件从创建到卸载的整个过程,每个过程都有对应的钩子函数会被调用,它主要有以下几个阶段:
挂载阶段 :组件实例被创建和插入 DOM 树的过程
更新阶段 :组件被重新渲染的过程
卸载阶段 :组件从 DOM 树中被删除的过程
componentWillMount发生在render之前,此时还没有挂载DOM,有可能会被执行多次
常用的钩子,在组件挂载成功之后调用,该过程组件已经成功挂载到了真实 DOM 上。
在props发生改变(父组件重新render或者更新props)时调用,这个钩子提供对 props 的监听,在 props 发生改变后,相应改变组件的一些 state。在这个方法中改变 state 不会二次渲染,而是直接合并 state。
这个钩子相当于一个阀门,返回一个布尔值,决定是否更新组件。
由于 react 父组件更新,必然会导致子组件更新,因此我们可以在子组件中通过手动对比 props 与 nextProps,state 与 nextState 来确定是否需要重新渲染子组件,如果需要则返回true,不需要则返回 false。该函数默认返回 true。
组件更新前调用的钩子
组件更新完成后调用的钩子
卸载阶段唯一的生命周期钩子,通常在这里处理一些善后工作,例如关闭定时器、取消监听等等
react 打算在17版本推出新的 Async Rendering(异步渲染),提出一种可被打断的生命周期,而可以被打断的阶段正是实际 dom 挂载之前的虚拟 dom 构建阶段,也就是要被去掉的三个生命周期。
该生命周期在 render方法之前调用,在初始化和后续更新都会被调用
它接收两个参数,一个是传进来的 nextProps 和之前的 prevState。他应该返回一个对象来更新 state。如果返回 null 则不更新任何内容。
这个生命周期主要为我们提供了一个可以在组件实例化或 props、state 发生变化后根据 props 修改 state 的一个时机。
在更新阶段 render 后挂载到真实 DOM 前进行的操作,它使得组件能在发生更改之前从 DOM 中捕获一些信息。此组件返回的任何值将作为 componentDidUpdate 的第三个参数。
代码如下:
import React from 'react';
const buildClass = (name)=>{
return class extends React.Component{
constructor(props) {
super(props);
console.log( name + ' constructor');
}
UNSAFE_componentWillMount() {
console.log( name + ' componentWillMount');
}
componentDidMount() {
console.log( name + ' componentDidMount');
}
componentWillUnmount() {
console.log( name + ' componentWillUnmount');
}
UNSAFE_componentWillReceiveProps(nextProps) {
console.log( name + ' componentWillReceiveProps(nextProps)');
}
shouldComponentUpdate(nextProps, nextState) {
console.log( name + ' shouldComponentUpdate(nextProps, nextState)');
return true;
}
UNSAFE_componentWillUpdate(nextProps, nextState) {
console.log( name + ' componentWillUpdate(nextProps, nextState)');
}
componentDidUpdate(prevProps, prevState) {
console.log( name + ' componetDidUpdate(prevProps, prevState)');
}
}
}
class Child extends buildClass('Child'){
render(){
console.log('Child render')
return (
<div>child</div>
)
}
}
class ClassFn extends buildClass('Parent'){
render(){
console.log('Parent render')
return (
<Child />
)
}
};
export default ClassFn;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。