React知识点汇总

541 阅读3分钟
原文链接: ghmagical.com
这篇文章并不会详细的介绍什么是React,如何使用React,而是整理React的知识点,可以让你更好的使用React。
1、生命周期
挂载阶段
getDefaultProps 获取默认propsgetInitialState 获取默认statecomponentWillMount 即将挂载render 挂载componentDidMount 组件渲染完成,可以在这里执行DOM操作等

更新阶段
componentWillReceiveProps 当props改变时shouldComponentUpdate 是否重新渲染,当返回true,表示渲染;否则不渲染,也就是不调用rendercomponentWillUpdate 即将重新渲染render 渲染componentDidUpdate 重新渲染完成
卸载阶段
componentWillUnmount 卸载组件

2、更新状态
在React中,使用setState()来更新状态。
还可以强制更新: forceUpdate()
注:React底层对setState()做了优化,也就是每次队列循环中,都会合并所有setState(),且只会渲染(render)一次。
3、事件
React采取驼峰法来绑定事件:onClick、onMouseDown等 注:不管是预订义事件还是自定义事件,回调函数的最后一个参数都是响应值,比如:预订义事件中的event

4、动画
动画推荐使用react-motion

5、组件通信
父 -> 子

通过props来通信
componentWillReceiveProps(nextProps) {   
  if ('name' in nextProps && this.props.name !== nextProps.name)    {   
     this.setState({   
       name: nextProps.name   
      })   
  }  
}

子 -> 父

通过事件属性来通信

class ChildComponent {
  render() {
    return (
      <div> <button onClick={this.props.onClick}>Button</button> </div>
    );
  }
}


class ParentComponent {
  state = {
    count: 0
  }
  onClick = () => {
    this.setState({
      count: this.state.count + 1
    })
  }


  render() {
    return (
      <div> <ChildComponent onClick={this.onClick}/> </div>
    );
  }
}

我们还可以通过统一状态机来管理,进而通信,下面将讲到。

6、Redux
统一状态管理store:
createStore()

action,可以看作一个动作的标识符和动作的结合。
const DO = 'DO';   


function do() {   
  return {   
    type: DO   
  }  
}
reducer,可看作是动作产生后的操作。
const defaultState = {   
  count: 1  
};   


function myData(state = defaultState, action) {   
  switch (action.type) {   
    case DO:   
      return {...state, ...{count: state.count + 1}};   
  }  
}
注:每次返回的必须是一个新state。

7、使用ES6中的Class来写组件
import * as React from 'react';   


class MyComponent extends React.Component {   
  static defaultProps = {   
    name: ''   
  };    
  
  constructor(props) {   
    super(props);   
    this.state = {};   
  }    


  componentDidMount() {}    


  render() {   
    return (<div>abc</div>);   
  }  
}

8、常用方法
React.createElement(type, [props], [...children])     创建React元素
React.cloneElement(element, [props], [...children])    克隆并生成一个新元素
React.isValidElement(object)   验证对象是否是一个React元素。返回 true 或 false 。

React.Children  

  map    遍历子元素,映射为一个新的子元素集合(跟 ES5 的 Array.map 差不多)

  forEach   遍历子元素,对每一个子元素执行回调,但是不返回一个新数组(跟 ES5 的 Array.forEach 差不多)

  count   返回子元素的总数

  only    返回 children 中的唯一子集。否则抛出异常。

  toArray  将 children 不透明数据结构作为一个平面数组返回,并且 key 分配给每个子集。