五大react使用注意事项

一、你知道初始化state的正确姿势吗?

相信有很多码友在初始化state的时候会使用以下的方式:

class ExampleComponent extends React.Component {state = {};componentWillMount() {this.setState({currentColor: this.props.defaultColor,palette: 'rgb',});}
}

这可就麻烦了,因为componentWillMount只会在加载阶段执行一次,虽然setState会引发render,但是这个时候还没有第一次render所以setState后我们的界面仍不会有改变。故而我们不应该在componentWillMount里进行state的初始化,正确的姿势请看下方代码

class ExampleComponent extends React.Component {state = {currentColor: this.props.defaultColor,palette: 'rgb',};
}
class ExampleComponent extends React.Component {constructor(props){super(props)this.state={currentColor: props.defaultColor,palette: 'rgb',}}

这两种方式都可以,没有优劣之分,但是如果你需要在constructor里面去绑定事件函数,就需要使用第二种啦

二、获取外部数据需要注意哦

我们搞一个页面,免不了的就是去获取外部数据,那究竟我们应该在何时何地获取它最为合理恰当呢?相信这也是多数才接触react的码友的困恼之处。我们先来看看容易犯错的地方,即在componentWillMonut里面去获取外部数据

class ExampleComponent extends React.Component {state = {externalData: null,};componentWillMount() {this._asyncRequest = loadMyAsyncData().then(externalData => {this._asyncRequest = null;this.setState({externalData});});}componentWillUnmount() {if (this._asyncRequest) {this._asyncRequest.cancel();}}render() {if (this.state.externalData === null) {// Render loading state ...} else {// Render real UI ...}}
}

大家都知道,componentWillMonut是在render之前被调用,也就是说这时候是还没有渲染出dom结构的,及时获取到数据也没有办法渲染到页面中,而且在之后即将到来的react17将采用异步渲染,componentWillMonuti将可能会被调用多次,如果在里面进行获取数据这些异步操作,会导致多次请求,所以正确的姿势如下

class ExampleComponent extends React.Component {state = {externalData: null,};componentDidMount() {this._asyncRequest = loadMyAsyncData().then(externalData => {this._asyncRequest = null;this.setState({externalData});});}componentWillUnmount() {if (this._asyncRequest) {this._asyncRequest.cancel();}}render() {if (this.state.externalData === null) {// Render loading state ...} else {// Render real UI ...}}
}

我们应该在componentDidMount里面进行获取外部数据操作,这时组件已经完全挂载到网页上,所以可以保证数据的加载。此外,在这方法中调用setState方法,会触发重渲染。所以,官方设计这个方法就是用来加载外部数据用的,或处理其他的副作用代码。
还有就是,我们如果需要进行订阅,也不要在componentWillMount里面进行订阅,应该在componentDidMount里面进行订阅,在componentWillUnmount里面取消订阅

三、根据props更新state

往往在比较复杂的页面中,我们免不了通过props传递属性给子组件,子组件通过props来更新自身的state,且看以往我们的做法:

class ExampleComponent extends React.Component {state = {isScrollingDown: false,};componentWillReceiveProps(nextProps) {if (this.props.currentRow !== nextProps.currentRow) {this.setState({isScrollingDown:nextProps.currentRow > this.props.currentRow,});}}
}

我们常常会在componentWillReceiveProps这个生命周期里去比较新旧props来更新state,但随着新的生命周期getDerivedStateFromProps的出现,我们就不应该再使用这种方式了,而应该使用getDerivedStateFromProps:

class ExampleComponent extends React.Component {// Initialize state in constructor,// Or with a property initializer.state = {isScrollingDown: false,lastRow: null,};static getDerivedStateFromProps(props, state) {if (props.currentRow !== state.lastRow) {return {isScrollingDown: props.currentRow > state.lastRow,lastRow: props.currentRow,};}// Return null to indicate no change to state.return null;}
}

您可能会注意到,在上面的示例中,该props.currentRow状态已镜像(如state.lastRow)。这样就可以getDerivedStateFromProps按照中的相同方式访问先前的props值componentWillReceiveProps。下面是官方给出的未提供prevProps的理由:

您可能想知道为什么我们不只是将先前的prop作为参数传递给getDerivedStateFromProps。我们在设计API时考虑了此选项,但最终出于以下两个原因而决定:

prevProps首次getDerivedStateFromProps调用(实例化之后)的参数为null
,要求在每次prevProps访问时都添加if-not-null检查。
不将先前的props传递给此功能是朝着将来的React版本释放内存的一步。(如果React不需要将先前的prop传递到生命周期,那么它就不需要将先前的props对象保留在内存中。)

四、props改变产生的副作用

有时候,当props改变时,我们会进行一些除更新state之外的操作,比如调用外部方法,获取数据等,以前我们可能一股脑的将这些操作放在componentWillReceiveProps中,像下面这样:

// Before
class ExampleComponent extends React.Component {componentWillReceiveProps(nextProps) {if (this.props.isVisible !== nextProps.isVisible) {logVisibleChange(nextProps.isVisible);}}
}

但这是不可取的,因为一次更新可能会调用多次componentWillReceiveProps,因此,重要的是避免在此方法中产生副作用。相反,componentDidUpdate应该使用它,因为它保证每次更新仅被调用一次:

class ExampleComponent extends React.Component {state = {externalData: null,};static getDerivedStateFromProps(props, state) {// Store prevId in state so we can compare when props change.// Clear out previously-loaded data (so we don't render stale stuff).if (props.id !== state.prevId) {return {externalData: null,prevId: props.id,};}// No state update necessaryreturn null;}componentDidMount() {this._loadAsyncData(this.props.id);}componentDidUpdate(prevProps, prevState) {if (this.state.externalData === null) {this._loadAsyncData(this.props.id);}}componentWillUnmount() {if (this._asyncRequest) {this._asyncRequest.cancel();}}render() {if (this.state.externalData === null) {// Render loading state ...} else {// Render real UI ...}}_loadAsyncData(id) {this._asyncRequest = loadMyAsyncData(id).then(externalData => {this._asyncRequest = null;this.setState({externalData});});}
}

像上面的代码一样,我们应该将状态更新与获取外部数据分离开来,将数据更新移至componentDidUpdate。

五、如何优雅的获取更新前的dom属性

我们常常会有这样的需求,就是在组件更新后我要保留一些更新前的属性,这就需要在更新前做相关的保存操作。在新的生命周期getSnapshotBeforeUpdate还没有出来之前,我们实现这一需求的方式就只有在componentWillUpdate去手动保存我们需要的属性,在componentDidUpdate里去使用:

class ScrollingList extends React.Component {listRef = null;previousScrollOffset = null;componentWillUpdate(nextProps, nextState) {// Are we adding new items to the list?// Capture the scroll position so we can adjust scroll later.if (this.props.list.length < nextProps.list.length) {this.previousScrollOffset =this.listRef.scrollHeight - this.listRef.scrollTop;}}componentDidUpdate(prevProps, prevState) {// If previousScrollOffset is set, we've just added new items.// Adjust scroll so these new items don't push the old ones out of view.if (this.previousScrollOffset !== null) {this.listRef.scrollTop =this.listRef.scrollHeight -this.previousScrollOffset;this.previousScrollOffset = null;}}render() {return (<div ref={this.setListRef}>{/* ...contents... */}</div>);}setListRef = ref => {this.listRef = ref;};
}

但是这样会有许多弊端,使用异步渲染时,“渲染”阶段生命周期(如componentWillUpdate和render)和“提交”阶段生命周期(如componentDidUpdate)之间可能会有延迟。如果用户在此期间进行了诸如调整窗口大小的操作,则scrollHeight从中读取的值componentWillUpdate将过时。

解决此问题的方法是使用新的“提交”阶段生命周期getSnapshotBeforeUpdate。在进行突变之前(例如在更新DOM之前)立即调用此方法。它可以返回一个值,以使React作为参数传递给componentDidUpdate,在发生突变后立即被调用。如下:

class ScrollingList extends React.Component {listRef = null;getSnapshotBeforeUpdate(prevProps, prevState) {// Are we adding new items to the list?// Capture the scroll position so we can adjust scroll later.if (prevProps.list.length < this.props.list.length) {return (this.listRef.scrollHeight - this.listRef.scrollTop);}return null;}componentDidUpdate(prevProps, prevState, snapshot) {// If we have a snapshot value, we've just added new items.// Adjust scroll so these new items don't push the old ones out of view.// (snapshot here is the value returned from getSnapshotBeforeUpdate)if (snapshot !== null) {this.listRef.scrollTop =this.listRef.scrollHeight - snapshot;}}render() {return (<div ref={this.setListRef}>{/* ...contents... */}</div>);}setListRef = ref => {this.listRef = ref;};
}

这两个生命周期一定是成双成对出现的,不然会报错,而且在getSnapshotBeforeUpdate中的返回值会直接作为componentDidUpdate的参数传递进去,并不需要我们去手动保存状态。十分的方便。

以上就是我对react的生命周期的用法的一些总结,如有不对之处,还望各位读者不吝赐教,谢谢大家。

五大react生命周期使用注意事项,绝对干货相关推荐

  1. 深入react技术栈(5):React生命周期

    我是歌谣 放弃很容易 但是坚持一定很酷 微信搜一搜前端小歌谣 React生命周期 挂载和卸载过程 组件得挂载 组件得卸载 数据更新过程 整体流程 文章参考深入学习React技术栈

  2. react学习(9)----react生命周期

    react生命周期1.1.constructor() constructor()中完成了React数据的初始化,它接受两个参数 :props和context,当想在函数内部使用这两个参数时 ,需使用s ...

  3. react生命周期(自己的方式理解)

    react生命周期(自己的方式理解) react的生命周期函数有:挂载,渲染/更新,卸载 首先要知道react生命周期最初始的要有哪些?最后生命中出现的又有哪些?我本人喜欢把react比作是一个人的一 ...

  4. 你不可不知道的React生命周期

    点小蓝字加关注! 作者:kim 来源:原创 写在前面 咱今天聊的话题是React生命周期,灵感来自于最近在网上发现一篇关于react生命周期的文章,里面记录的知识点竟然与小编所get到的有出入.作为一 ...

  5. ES6中的React生命周期详解

    太长时间没写react了,有点生.重新捡起来练练手. import React,{ Component } from 'react';class Demo extends Component {con ...

  6. react生命周期方法介绍

    react生命周期 react生命周期主要包括三个阶段:初始化阶段.运行中阶段.销毁阶段 react在不同的生命周期会触发不同的钩子函数 初始化阶段 getDefaultProps() 设置组件默认的 ...

  7. react生命周期详细介绍

    目录 挂载:在组件实例被创建并插入到dom中时,生命周期调用顺序如下 constructor componentWillMount getDerivedStateFromProps render co ...

  8. vue生命周期和react生命周期对比。

    生命周期 指的是组件从初始化开始到结束的过程 或者是生命周期是描述组件从开始到结束的过程,每个组件都具有生命周期,都对组件通过生命周期给予的钩子函数进行管理. 钩子函数 指的是系统某些状态和参数发生改 ...

  9. React、react生命周期、react生命周期运行过程、shouldComponentUpdate的用法

    React.react生命周期.react生命周期运行过程 1.创建阶段 constructor(){super()console.log('执行构造函数')this.state={num:1}}UN ...

最新文章

  1. 多个CALayer的联动
  2. mongodb 内建用户
  3. java获取年初年末_Java用于取得当前日期相对应的月初,月末,季初,季末,年初,年末时间...
  4. for循环中++i和i++的区别
  5. python设计一个函数定义计算并返回n价调和函数_音乐编程语言musicpy教程(第三期) musicpy的基础语法(二)...
  6. 三年经验前端社招——有赞
  7. 字典树模板+洛谷P2580 于是他错误的点名开始了
  8. 使用Struts2,Hibernate和MySQL创建个人MusicManager Web应用程序的研讨会
  9. CountDownLatch/CyclicBarrie用法记录
  10. 独立物理机和虚拟机比较有什么优势?
  11. 【java】 Java 类加载器 破坏双亲委派
  12. 云栖日报丨收购中天微,阿里芯了解一下!
  13. 凸优化有关的数值线性代数知识 4分块消元与Schur补
  14. OA 系统中的流程管理
  15. 数学专业考研计算机,过来人谈数学专业考研:万学之基 万物皆数也
  16. ws office excel 基础公式
  17. 战狼2影评-20170807
  18. 31岁,追忆似水流年。。。
  19. 爆笑!让你捧腹大笑的标语
  20. Oracle日期格式转换 to_date,to_char,to_timetamp 相互转换

热门文章

  1. BZOJ——2134: 单选错位
  2. Python:Anaconda安装虚拟环境到指定路径
  3. TCP协议之三次握手与四次挥手
  4. SQL 必知必会·笔记7汇总数据——使用聚合函数
  5. MS SQL入门基础:sql 其它命令
  6. 四种方式话Equal
  7. Webpack实战(六):如何优雅地运用样式CSS预处理
  8. 【Vue】全局过滤器和局部过滤器
  9. LeetCode--95. 不同的二叉树搜索Ⅱ(动态规划)
  10. 车牌识别EasyPR(4)——字符识别MSER