React-生命周期与其他,diffing算法的理解
3.组件生命周期钩子

- 组件挂载之前[弃用]
- componentWillMount(){
- 组件渲染,状态更新之后
- render(){}
- 组件挂载完毕
- class中函数:componentDidMount(){//somedoing}
- 组件卸载之前
- class中函数:componentWillUnmount(){//somedoing}
—
- 是否应该更新组件
- shouldComponentUpdate(){//default return true}
- 强制组件更新API
- this.forceUpdate()
- 组件将要更新[弃用]
- componentWillUpdate(){}
- 组件完成更新
- componentDidUpdate([preprop,prestate,snapshot]){}
- 卸载组件
- React.unmountComponentAtNode(document.getElementById(“容器id”))
- 父组件render流程中componentWillReceiveProps([props]){}[弃用]
该函数写在子组件中,首次加载不会调用,后续更新才会触发该函数

- 阻止state更新,并且将props值[接受prop参数情况下]作为state
- 使用场景:state取决于props
- 返回值为{}json对象,使用该函数将会阻止state的更新
- 返回值为null,state每次更新该函数都会调用一次
- static getDerivedStateFromProps(props = null)
- 组件更新完成之前的快照
- getSnapshotBeforeUpdate
- 作用就是在组件将要出现的时候处理一些数据
class Myform extends React.Component{
state = {
c: 0
}
addc = ()=>{
this.state.c+=1
this.setState({c: this.state.c})
}
//强制更新,触发componentWillUpdate->render->conponentDidUpdate
forc = ()=>{
this.forceUpdate();
}
//阻止state更新,并且将props值[接受prop参数情况下]作为state
static getDerivedStateFromProps(props = null){
console.log("getDreiveStateFromProps-阻止state更新,并且将props值[接受prop参数情况下]作为state",props)
return null;
}
//组件挂载-之前
componentWillMount(){
console.log('组件挂载-之前');
}
//组件渲染,状态更新之后
render(){
console.log('组件渲染,状态更新之后');
let c = this.state.c;
return (
<div>
<p>{c}</p>
<button onClick={this.addc}>+1</button>
<button onClick={this.forc}>强制更新</button>
</div>
)
}
//组件挂载-完毕
componentDidMount(){
console.log('组件挂载-完毕');
}
//组件卸载-之前
componentWillUnmount(){
console.log('组件卸载-之前');
}
//是否应该更新组件
shouldComponentUpdate(){
console.log('是否应该更新组件');
return true;
}
//组件将要更新
componentWillUpdate(){
console.log('组件将要更新');
}
//组件完成更新
componentDidUpdate(){
console.log('组件完成更新');
}
}
ReactDOM.render(<Myform />,document.getElementById("app"))
4.DOM的Diffng算法
组件更新的最小粒度是标签,但不仅限于标签里的内容是否改变;而是对标签内容进行深度检查,不是只对标签”表层”内容,因此含有状态更新的标签里存在的input并不会被diff算法重新渲染更新;
为什么使用index作为key效率低/为什么不建议使用index作为key
简单说就是使用index可能导致react重复生成新的dom,效率低
详细点就是,react在数据更新时候,会生成一个新虚拟dom;然后将旧虚拟dom与新虚拟dom比较;如果:
key相同
比较内容,内容相同就用之前的真实dom,内容不同就生成新的真实dom并覆盖之前的
key不同(不存在)
生成新的真实dom
我学习React的更新或者更详细的学习过程将会在石墨文档中记录,https://shimo.im/docs/h3y3rgY3xCP6CRcw/ 「React」,可复制链接后用石墨文档 App 或小程序打开
快捷登陆