概览
在React应用的入口会执行createRoot方法,而createRoot方法最后会返回ReactDOMRoot的实例对象
js
function createRoot(){
....
return new ReactDOMRoot(options)
}
本文主要介绍ReactDOMRoot的实现。
源码分析
ReactDOMRooT就是一个普通的函数,在其原型上定义了render和unmount方法,分别用于挂载渲染子节点和卸载应用。
js
function ReactDOMRoot(internalRoot) {
// 存储内部的Fiber 根节点
this._internalRoot = internalRoot;
}
/**
* createRoot(div).render(<App/>) render方法的实现就是如下
*/
ReactDOMRoot.prototype.render =
function (children) {
// 获取内部根节点
var root = this._internalRoot;
// 确保根节点存在
if (null === root) throw Error(formatProdErrorMessage(409));
// 获取当前的Fiber树根节点
var current = root.current,
// 请求一个更新车道:优先级
lane = requestUpdateLane();
// 调用 updateContainerImpl更新容器
updateContainerImpl(current, lane, children, root, null, null);
};
/**
* unmount方法:卸载应用的方法,会清理整个React应用
*/
ReactDOMRoot.prototype.unmount =
function () {
var root = this._internalRoot;
// 若根节点存在,则执行卸载
if (null !== root) {
// 清空内部节点引用
this._internalRoot = null;
// 获取容器DOM元素
var container = root.containerInfo;
// 第三个参数为null,表示卸载所有子节点,lane=2表示同步更新
updateContainerImpl(root.current, 2, null, root, null, null);
// 强制同步刷新工作,确保立即卸载
flushSyncWork$1();
// 清理容器DOM元素上的内部实例标记
container[internalContainerInstanceKey] = null;
}
};