React.Component概览与解析

2019-07-30  本文已影响0人  Ahungrynoob

Component的源代码在ReactBaseClasses.js中。

生命周期:

挂载:

组件实例化并插入dom之前,以下方法将会按照顺序执行

注意:

以下方便应该尽可能地避免使用:

更新

组件更新并重新渲染时,会按顺序触发以下方法:

注意:

应该尽量避免使用这些方法:

卸载时

组件从dom卸载时会调用以下方法:

错误处理

渲染过程中如果有异常抛出,或者自组建的构造函数中有异常抛出,会触发以下方法:

其他APIs

每个组件实例也会提供一些api:

Class Static Properties

Instance Properties

componentDidUpdate(prevProps, prevState, snapshot)

如果你的组件实现了 getSnapshotBeforeUpdate() 生命周期方法 (少见情况), 这个方法返回的值将作为第三个参数 “snapshot” 传给 componentDidUpdate(). 否则这个参数将会是undefined.

getDerivedStateFromProps:

getDerivedStateFromProps 的存在只有一个目的:让组件在 props 变化时更新
state。官方给了两个例子: props 的 offset 变化时,修改当前的滚动方向根据 props 变化加载外部数据

getSnapshotBeforeUpdate

在componentDidUpdate之前,处理scroll位置业务逻辑时有奇效

错误边界

错误边界能catch住子组件的render、constructor以及生命周期中的异常,但无法捕捉自己的异常

static getDerivedStateFromError

如果子组件有异常抛出,这个方法将会被触发。它会接受一个子组件抛出的错误参数,并在state中体现,render中去处理。

componentDidCatch

componentDidCatch生命周期适合做错误日志的收集和上报。UI的展示就交给getDerivedStateFromError来吧。

componentWillMount

componentWillMount的名字在17版本以后会失效,新名字是UNSAFE_componentWillMount. 使用 rename-unsafe-lifecycles codemod 去自动替换你的代码中的componentWillMount方法吧

componentWillReceiveProps

componentWillReceiveProps的名字在17版本以后会失效,新名字是UNSAFE_componentWillReceiveProps. 使用 rename-unsafe-lifecycles codemod 去自动替换你的代码中的componentWillReceiveProps方法吧

注意
父组件重新render时,会触发子组件的componentWillReceiveProps方法,尽管props没有变化,所以这个方法中要对props的变化做判断,避免无止尽的render。
另外子组件自己的state变更造成的render不会触发这个方法

componentWillUpdate

componentWillUpdate的名字在17版本以后会失效,新名字是UNSAFE_ componentWillUpdate. 使用 rename-unsafe-lifecycles codemod 去自动替换你的代码中的componentWillUpdate方法吧
提示: 这个方法基本没啥用,也不能setState,一些side-effect可以放在getSnapshotBeforeUpdate中去做。

portal

Portals 提供了将可渲染元素挂载到其他dom节点下的能力,特别适合弹窗,工具条组件等。

注意
在虚拟dom中,父组件依然能捕捉到子组件的冒泡事件,尽管在真实dom树中,他们并不是父子的结构。

上一篇 下一篇

猜你喜欢

热点阅读