React 生命周期

初始化阶段

由ReactDOM.render() 触发 ---初次渲染

  1.  constructor() 
  2.  componentWillMount()  组件将要被渲染
  3.  render() ====>一定用 开始渲染组件
  4.  componentDidMount() ==> 常用 一般在这个钩子中做一些初始化的事,例如 开启定时器 发送网络请求 订阅消息

更新阶段

由组件内部 this.setState() 或父组件render触发

  1.  componentWillReceiveProps(props)  父组件更新了新的 props
  2.  shouldComponentUpdate()  是否要更新组件
  3. 使用 this.forceUpdate() 可跳过上一步  直接更新
  4.  componentWillUpdate()  组件即将要更新
  5.  render() ====> 再次渲染更新
  6.  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>
      )
    }
  }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值