[关闭]
@c-Ku 2017-11-27T11:05:36.000000Z 字数 1508 阅读 677

React 生命周期

ReactJS JavaScript cNotes


最新版:https://www.zybuluo.com/c-Ku/note/808873

实例化

当组件在客户端被实例化,第一次被创建时,以下方法被调用:

1. getDefaultProps

只调用一次,用于设置 props 的值。

2. getInitialState

只调用一次,用于初始化每个实例的 State,在该方法里可以访问组件的porps。
如果使用ES6的语法,可以在构造函数中初始化状态
如:constructor (props)

3. componentWillMount

在首次渲染前调用,也是在render加载前最后一次修改 state 的机会。

4. render

该方法会创建一个虚拟Dom,用来表示组件的输出
且只能通过 this.state 和 this.props 访问数据
可以返回 null、false 或 任何react组件
只能出现一个顶级组件,不能返回一组元素

5. componentDidMount

该组件不会在服务端渲染的过程中调用
调用时,真实的Dom已经生成
可通过 this.getDOMNode()this.findDOMNode()

示例:

  1. var Area = React.createClass({
  2. render: function(){
  3. this.getDOMNode()
  4. //render调用时,组件未挂载,这里将报错
  5. return <canvas ref='mainCanvas'>
  6. },
  7. componentDidMount: function(){
  8. var canvas = this.refs.mainCanvas.getDOMNode();
  9. //这是有效的,可以访问到 Canvas 节点
  10. }
  11. })

存在期

当组件渲染好,且用户已经可以进行交互(如点、触),可改变应用状态时,下面的方法会被依次调用

1. componentWillReceiveProps

父组件更改 props 时被调用
可在该方法内更新State,而触发 render 方法重新渲染组件

示例:

  1. componentWillReceiveProps: function (nextProps) {
  2. if (nextProps.checked !== undefined) {
  3. this.setState({
  4. checked: nextProps.checked
  5. })
  6. }
  7. }

2. shouldComponentUpdate

若确定组件的 props 或者 state 的改变不需重新渲染
可用该方法返回 false 来阻止事件的重新渲染
之后便不会执行 render 以及后面的 componentWillMount 和 componentDidUpdate
react.PureComponent 才有该方法

3. componentWillUpdate

和 componentWillMount 类似
组件接受到 props 或者 state 即将重新渲染前
会对以下形式方法进行调用
componentWillUpdate(object nextProps, object nextState)
使用此方法时切勿修改 props 和 state

4. componentDidUpdate

和 componentDidMount 类似
组件将要重新渲染前,会对以下形式方法进行调用
componentDidUpdate(object prevProps, object prevState)
在这里可以访问并修改DOM

销毁时

1. componentWillUnmount

每当 react 用完一个组件,这个组件必须从DOM中卸载并销毁
此时该方法会被执行,完成所有的清理和销毁工作
在 componentDidMount 中添加的任务都需要在该方法中撤销
如创建的 定时器 或事件监听器

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注