初始化阶段
由ReactDOM.render() 触发 ---初次渲染
- constructor()
- componentWillMount() 组件将要被渲染
- render() ====>一定用 开始渲染组件
- componentDidMount() ==> 常用 一般在这个钩子中做一些初始化的事,例如 开启定时器 发送网络请求 订阅消息
更新阶段
由组件内部 this.setState() 或父组件render触发
- componentWillReceiveProps(props) 父组件更新了新的 props
- shouldComponentUpdate() 是否要更新组件
- 使用 this.forceUpdate() 可跳过上一步 直接更新
- componentWillUpdate() 组件即将要更新
- render() ====> 再次渲染更新
- componentDidUpdate() 完成更新
卸载组件
由ReactDOM.unmountComponentAtNode(‘#root’)触发
componentWillUnmount() ===> 常用 一般在这个钩子中做一些收尾的事 例如 关闭定时器 取消消息订阅
新版变化:
改名了三个带Will的钩子 后期可能会移除 (react 主方向为异步渲染 这几个不常用有可能会起到副作用)
componentWillMount => UNSAFE_componentWillMount
componentWillReceiveProps => UNSAFE_componentWillReceiveProps
componentWillUpdate => UNSAFE_componentWillUpdate
新增了两个钩子
getDerivedStateFromProps
derived 衍生 获得衍生状态从 props 中
1.必须是静态属性 2.必须要有返回值
// 若state 的值在任何时候都取决于 props, 那么可以使用getDerivedStateFromProps()
static getDerivedStateFromProps(props,state){
console.log('getDerivedStateFromProps',props,state)
return null
}
getSnapshotBeforeUpdate
// 可以返回想记录的 数据(更新前) 快照 也是必须要有 return 值
然后在componentDidUpdate(preProps,preState,snapshotValue) 当中可以接收
小案例:
容器设置高度 溢出显示滚顶条
计时器每秒自增一条数据 渲染到容器当中
更新 记录 容器的scrollHeight 被滚进去高度 return 出去
在 componentDidUpdate 接收 使得scrollHeight 不会随着数据的增加而滚动
// 测试 getSnapshotBeforeUpdate 快照使用场景
class Test extends React.Component{
state={newList:[]}
componentDidMount(){
setInterval(()=>{
let index = this.state.newList.length + 1
const arr = `新闻 ${index}`
this.setState({
newList: [arr,...this.state.newList]
})
},1000)
}
getSnapshotBeforeUpdate(){
return this.refs.list.scrollHeight
}
componentDidUpdate(preProps,preState,height){
this.refs.list.scrollTop += this.refs.list.scrollHeight - height
}
render(){
return(
<div className="scrollY" ref="list">
{
this.state.newList.map((n,index)=>{
return <div key={index} className="news">{n}</div>
})
}
</div>
)
}
}