ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

react新的生命周期

2019-08-08 23:04:05  阅读:292  来源: 互联网

标签:生命周期 函数 nextProps 渲染 nextState react state 组件


原文链接:http://www.cnblogs.com/colima/p/9484607.html

一. react16当前生命周期

  • componentWillMount
    render前,所以setState不会重新渲染,服务端渲染唯一调用,推荐用constructor代替之
  • render
  • componentDidMount
    render后,调用setState会重新渲染,页面可交互,可以请求数据
  • componentWillRecieveProps(nextProps)
    已挂载组件接收到新props触发
  • shouldComponentUpdate(nextProps, nextState)
    在接收到新的props或state时是否重新渲染,默认返回true;首次渲染或forceUpdate时不会触发;
  • componentWillUpdate(nextProps, nextState)
    如果shouldComponentUpdate返回false,update相关的函数都不会触发;不要使用setState;
  • componentDidUpdate(nextProps, nextState)
  • componentWillUnmount
    卸载组件

二. 由于未来采用异步渲染机制,所以即将在17版本中去掉的生命周期钩子函数

  • componentWillMount
  • componentWillRecieveProps
  • componentWIllUpdate

三. 新增两个

  • static getDerivedStateFromProps
    会在初始化和update时触发,用于替换componentWillReceiveProps,可以用来控制 props 更新 state 的过程;它返回一个对象表示新的 state;如果不需要更新,返回 null 即可
  • getSnapshotBeforeUpdate
    用于替换 componentWillUpdate,该函数会在update后 DOM 更新前被调用,用于读取最新的 DOM 数据,返回值将作为 componentDidUpdate 的第三个参数

四. 建议用法

class A extends React.Component {
  // 用于初始化 state
  constructor() {}
  // 用于替换 `componentWillReceiveProps` ,该函数会在初始化和 `update` 时被调用
  // 因为该函数是静态函数,所以取不到 `this`
  // 如果需要对比 `prevProps` 需要单独在 `state` 中维护
  static getDerivedStateFromProps(nextProps, prevState) {}
  // 判断是否需要更新组件,多用于组件性能优化
  shouldComponentUpdate(nextProps, nextState) {}
  // 组件挂载后调用
  // 可以在该函数中进行请求或者订阅
  componentDidMount() {}
  // 用于获得最新的 DOM 数据
  getSnapshotBeforeUpdate() {}
  // 组件即将销毁
  // 可以在此处移除订阅,定时器等等
  componentWillUnmount() {}
  // 组件销毁后调用
  componentDidUnMount() {}
  // 组件更新后调用
  componentDidUpdate() {}
  // 渲染组件函数
  render() {}
  // 以下函数不建议使用
  UNSAFE_componentWillMount() {}
  UNSAFE_componentWillUpdate(nextProps, nextState) {}
  UNSAFE_componentWillReceiveProps(nextProps) {}
}

 

转载于:https://www.cnblogs.com/colima/p/9484607.html

标签:生命周期,函数,nextProps,渲染,nextState,react,state,组件
来源: https://blog.csdn.net/weixin_30484247/article/details/98889811

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有