Component和PureComponent

2020-06-22  本文已影响0人  skoll

React.Component

1 .使用ES6 classes方式定义React 组件
2 .不要创建自己的组件基类,推荐的是组合而不是继承
3 .组件的生命周期
3.1 挂载时

1 .constructor()
2 .static getDerivedStateFromProps()
3 .render()
4 .componentDidMount()

3.2 更新时

1 .static getDerivedStateFromProps()
2 .shouldComponentUpdate()
3 .render()
4 .getSnapshotBeforeUpdate()
5 .componentDidUpdate()

3.3 卸载时

componentWillUnmount()

3.4 错误处理

1 .static getDerivreStateFromError()
2 .componentDidCatch()

render()

1 .render方法是class组件中唯一需要实现的方法
2 .当render被调用的时候,他会检查this.props,this.state的变化并返回一下类型之一

1 .React元素:通常通过JSX创建。<div />会被React渲染为DOM节点,<MyComponent />会被渲染为自定义组件,不论是div,还是MyComponent均为React元素
2 .数组或者fragments。使得render方法可以返回多个元素
3 .Portals:可以渲染子节点到不同的DOM子树中去
4 .字符串或数值类型。在DOM中会被渲染为文本节点
5 .布尔类型或null,什么都不渲染

3 .render应该是纯函数,不修改组件组件state的情况下,每次调用都返回相同的结果
4 .如果shoudlComponentUpdate返回false,是不会调用render的

constructor()

1 .通过this.state赋值对象来初始化内部state
2 .为事件处理函数绑定实例
3 .这个里面不要调用setState,如果组件需要初始化,直接使用this.state赋值初始化
4 .避免将props的值赋值给state,就是bug

constructor(props) {
 super(props);
 // 不要这样做
 this.state = { color: props.color };
this.props.color
}
上一篇下一篇

猜你喜欢

热点阅读