从一个warning入手----熟悉React生命周期

之前刚刚接触React的时候,会犯的一个错误。

Warning: setState(…): Cannot update during an existing state transition (such as within render or another component’s constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.

setState(...)不能在存在的状态转换期间使用。(例如:在render方法或另一个组件的构造函数内)。render方法应该是propsstate的纯函数;可以将部分constructor下的state的更新转译到componentWillMount函数处理。

下面主要讲一下关于react的生命周期。hh

这里写图片描述

目录

挂载: 组件状态的初始化

class Demo extends Component{
    static propTypes = {};
    static defaultTypes = {};
    constructor() {

    }
    conponentWillMount() {
    }
    conponentDidMount() {
    }
    render() {
    }
}

propTypesdefaultTypes是React组件的类型检查和默认类型。定义成es6的静态类型,静态类型是什么捏:(https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes/static

static 关键字为一个类定义了一个静态方法。静态方法不会在类的实例上被调用。相反,他们被类本身调用。这些通常是实用程序方法,例如创建或克隆对象的功能。

触发组件挂载的顺序依次为:
constructor(初始化) ->
componentWillMount(渲染前) ->
render(渲染) ->
componentDidMount(渲染后)

constructorcomponentWillMountsetState会被合并为一次。

componentDidMount可以获取ref定义的真实的DOM了。

渲染

class Demo extends Component{
    componentWillReceiveProps(nextProps, nextState) {
    }
    shouldComponentUpdate(nextProps, nextState) {
    }
    componentWillUpdate(nextProps, nextState) {
    }
    componentDidUpdate(nextState, prevState) {
    }
}

触发一个组件重新渲染的事件顺序是:

componentWillReceiveProps:

有一种组件叫无状态组件,自身没有状态,全部是通过传入的参数来控制渲染,这种组件就需要通过这个方法,当传入的props变更的时候,变更自身的state,来触发render方法。

shouldComponentUpdate:

关于react的渲染,是在内存中维护一颗javascript描绘的虚拟DOM树,如果从顶层变更一个值,会去所有子节点(子组件)遍历。寻找变更。如果这个方法返回false,可以跳过比较。是一种剪枝手段。

componentWillUpdate:

不要在此方面里再去更新 props 或者 state。

render

渲染方法。

componentDidUpdate

componentDidMount一样,可以获取变更之后的DOM啦。

卸载

class Demo extends Component{
    componentWillUnmount() {
    }
}

componentWillUnmount:

卸载前的毁掉,主要是去销毁定时器,销毁注册的事件等等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值