两种React组件:class/FC
React组件与一般class/function的区别仅仅在于React组件承担更新UI的作用,此外与普通class/function无区别
两种组件的区别:
Fiber步骤根据不同Tag区分两种组件,分别按照各自方式处理
类组件实例化方式执行
Class组件的定义
function Component(props, context, updater) {
this.props = props; //绑定props
this.context = context; //绑定context
this.refs = emptyObject; //绑定ref
this.updater = updater || ReactNoopUpdateQueue; //上面所属的updater 对象
}
/* 绑定setState 方法 */
Component.prototype.setState = function(partialState, callback) {
this.updater.enqueueSetState(this, partialState, callback, 'setState');
}
/* 绑定forceupdate 方法 */
Component.prototype.forceUpdate = function(callback) {
this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
}
*当你写的组件里调用Super()不传props,由上面代码可看出最终会使得组件实例里的props为undefined
- ECMA262[Prototype]相关机制: 属性屏蔽等(见YDJS 上卷)
函数组件直接执行函数
类组件React只会实例化一次,每次有state更新仅重新执行render方法和相关类组件生命周期 (带有状态的组件) 函数组件在hooks出现前为无状态组件,无法保存state。因为仅仅是函数的执行
React组件通信
- props 和 callback 方式
- ref 方式。
- React-redux 或 React-mobx 状态管理方式。
- context 上下文方式。
- event bus 事件总线。
Event Bus用发布订阅模式的方式管理组件状态 顶多用在小程序上,不建议在React中使用。因为:它需要手动解绑,且有违反React数据流规则,难以维护
组件强化
1, 类组件继承
2, 函数组件自定义Hooks
3, HOC