reactReactWeb前端之路

深入React技术栈:React数据流和生命周期

2017-04-11  本文已影响404人  FeRookie

数据流

在React中,数据是单向流动的,是从上向下的方向,即从父组件到子组件的方向。
state和props是其中重要的概念,如果顶层组件初始化props,那么React会向下遍历整颗组件树,重新渲染相关的子组件。其中state表示的是每个组件中内部的的状态,这些状态只在组件内部改变。
把组件看成是一个函数,那么他接受props作为参数,内部由state作为函数的内部参数,返回一个虚拟dom的实现。

生命周期

了解React的生命周期对React的使用会有更好的理解,可以让自己的代码写的更加合理。
广义的可以将React分为挂载,渲染,卸载这几个阶段,当渲染后的组件需要更新,我们会重新去渲染组件,直至卸载。

import React , {Component, PropTypes} from 'react'

class App extends Component {
    static propTypes = {
        
    }
    
    static defaultProps = {
        
    }
    
    constructor(props) {
        super(props)
        this.state = {
            
        }
    }
    
    componentWillMount() {
        
    }
    componentDidMount() {
        
    }
    render() {
        
    }
    
}

首先我们看下上面的代码结构,propTypes和defaultProps分别代表的是props的类型检查和默认类型值。这两个属性声明为组件的静态属性,所以可以通过类对其进行访问。如: App. defaultProps。

然后可以看到componentWillMount这个方法,会在render方法之前执行,componentDidMount方法会在render方法之后执行,分别代表了渲染前和渲染后的阶段。

以上的过程都只会在组件初始化的时候执行一次,如果是在componentWillMount中执行了setState方法是无意义的,因为组件只渲染一次。在componentDidMount中执行setState方法组件会再次更新,这样初始化的时候就渲染了两次。在必要的情况下可以在componentDidMount执行setState方法。

import React, {Component, PropTypes} from 'react'

class App extends Component {
    componentWillReceiveProps(nextProps){
        // this.setState
    }
    
    shouldComponentUpdate(nextProps, nextState){
        //return true
    }
    
    componentWillUpdate(nextProps, nextState){
        
    }
    
    componentDidUpdate(preProps, preState){
        
    }
    
    render() {
        
    }
}

如上关于组件更新的生命周期需要使用到的方法。
如果是组件自身的state发生改变,那么依次会执行shouldComponentUpdate,componentWillUpdate,render, componentDidUpdate。

shouldComponentUpdate方法,该方法接受需要更新的props和state,方法返回FALSE的时候表示不进行更新,接下来的生命周期方法不会再执行下去,默认返回的是TRUE表示确定进行更新。

注意我们不可以在componentWillUpdate中执行setState方法。

在shouldComponentUpdate方法之前,还有一个componentWillReceiveProps方法,该方法在数据是有父组件的props更新的时候会触发,在此方法中执行setState方法是不会进行二次渲染的。

上一篇 下一篇

猜你喜欢

热点阅读