深入react技术栈 读书笔记

第一章

1.1.2 Virtual DOM

React把真实DOM转换成JavaScript对象树,也就是Virtual DOM
《深入react技术栈 读书笔记》
每次数据更新后,重新计算virtualDOM,并和上次生成的virtual树进行对比,对发生变化的部分做批量更新。

1.2.1 JSX语法

React 是通过创建与更新虚拟元素(virtual element)来管理整个 Virtual DOM 的。
虚拟元素分为DOM元素(DOM element)和组件元素(component element)。分别对应原生DOM元素与自定义元素。首字母小写对应原生Dom首字母大写对应组件元素。
JSX就负责创建这些元素。
1.DOM元素可以被表示成纯粹的json对象。

<button class="btn btn-blue"> 
  <em>Confirm</em> 
</button>
//转化成json对象
{ 
  type: 'button', 
      props: { 
      className: 'btn btn-blue', 
      children: [{ 
          type: 'em', 
          props: { 
              children: 'Confirm' 
          } 
      }] 
  } 
}

这样就在JavaScript中创建了virtualdom元素。
2.组件元素:组件元素的目的就是为了生成json对象形式的virtualdom。以上button为例,得到一种构建按钮的公共方法:

const Button = ({ color, text }) => { 
  return { 
      type: 'button', 
      props: { 
          className: `btn btn-${color}`, 
          children: { 
              type: 'em', 
              props: { 
                  children: text, 
              }, 
          }, 
      }, 
  }; 
}


1.5.1 生命周期初始化过程

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

class App extends Component { 
  static propTypes = { //props类型检查
      // ... 
  }; 
  static defaultProps = { //props默认类型
      // ... 
  }; 
  constructor(props) { 
      super(props); 
      this.state = { 
          // ... 
      }; 
  } 
  componentWillMount() { //在render方法之前执行,代表渲染前时刻
      // 在此执行this.setState,组件会更新state,但是此刻组件还未渲染毫无意义,初始化state应放在this.state中
  }
  componentDidMount() { //在render方法之后执行,代表渲染后时刻
      // 在此执行this.setState,组件会更新,不过在初始化过程中就进行了两次初始化。虽然不是一个好事,但有些场景不得不使用setState
      // 可以获取真正的dom元素
  }
   componentWillUnmount() { 组件的卸载
      // 在此会执行一些清理方法,比如事件回收和清除定时器
  }
  render() { 
     return <div>This is a demo.</div>; 
  } 
}


1.5.2 生命周期数据更新过程

更新过程指的是父组件向下传递props或者组件自身执行setState方法时发生的一系列更新过程

import React, { Component, PropTypes } from 'react'; 
class App extends Component { 
  componentWillReceiveProps(nextProps) { 
      // this.setState({}) 
  } 
  shouldComponentUpdate(nextProps, nextState) { 
      // return true; 
  } 
  componentWillUpdate(nextProps, nextState) { //代表更新过程中渲染前的时刻
      // 提供需要更新的props和state,此处不能指执行setState,可以获取真正的dom元素
  } 
  componentDidUpdate(prevProps, prevState) { //代表更新过程中渲染后的时刻
      // 提供更新前的props和state
  } 
  render() { 
      return <div>This is a demo.</div>; 
  } 
}

1.如果组件自身的state更新了,会依次执行shouldComponentUpdate,componentWillUpdate,componentDidUpdate。
shouldComponentUpdate是一个特别的方法,它接收将要更新的props和state,让开发者增加判断的条件,即让其在需要时更新,不需要时不更新。返回false组件就不再向下更新,此周期默认返回true。
shouldComponentUpdate从另一个意义上说,也是性能优化的手段之一。如下两图。

《深入react技术栈 读书笔记》
《深入react技术栈 读书笔记》
当props节点改变的时候,最理想的状况就是只更新被改变的那条链,通过改变shouldComponentUpdate返回true/false可以实现。
2.如果组件是由父组件更新props而更新的在执行shouldComponentUpdate前会先执行componentWillReceiveProps方法。在此方法中调用setState方法不会二次渲染。

1.5.3 整体流程

《深入react技术栈 读书笔记》

    原文作者:harden
    原文地址: https://segmentfault.com/a/1190000019906898
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞