正文
(
node(这里node指element
),
shouldHaveDebugID
) {
...
if
(node ===
null
|| node ===
false
) {
instance = ReactEmptyComponent.create(instantiateReactComponent);
}
else
if
(
typeof
node ===
'object'
) {
...
if
(
typeof
element.type ===
'string'
) {
instance = ReactHostComponent.createInternalComponent(element);
}
else
if
(isInternalComponentType(element.type)) {
}
else
{
instance =
new
ReactCompositeComponentWrapper(element);
}
}
else
if
(
typeof
node ===
'string'
||
typeof
node ===
'number'
) {
instance = ReactHostComponent.createInstanceForText(node);
}
else
{
invariant(
false
,
'Encountered invalid React node of type %s'
,
typeof
node);
}
...
return instance;
}
3、批量更新
在调用
instantiateReactComponent
拿到组件实例后, React 接着调用了
batchingStrategy.batchedUpdates
并将组件实例当作参数执行批量更新.
批量更新是一种优化策略, 避免重复渲染, 在很多框架都存在这种机制. 其实现要点是要弄清楚何时存储更新, 何时批量更新.
在React中, 批量更新受
batchingStrategy
控制,而这个策略除了server端都是
ReactDefaultBatchingStrategy
:
不信你看, 在ReactUpdates.js中 :
var ReactUpdatesInjection = {
...
injectBatchingStrategy: function(_batchingStrategy) {
...
batchingStrategy = _batchingStrategy;
},
};
在ReactDefaultInjection.js中注入
ReactDefaultBatchingStrategy
:
ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy);
那么React是如何实现批量更新的? 在ReactDefaultBatchingStrategy.js我们看到, 它的实现依靠了
事务
.
3.1 我们先介绍一下事务.
在 Transaction.js中, React 介绍了事务:
* <pre>
* wrappers (injected at creation time)
* + +
* | |
* +-----------------|--------|--------------+
* | v | |
* | +---------------+ | |
* | +--| wrapper1 |---|----+ |
* | | +---------------+ v | |
* | | +-------------+ | |
* | | +----| wrapper2 |--------+ |
* | | | +-------------+ | | |
* | | | | | |
* | v v v v | wrapper
* | +---+ +---+ +---------+ +---+ +---+ | invariants
* perform(anyMethod) | | | | | | | | | | | | maintained
* +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|-------->
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +---+ +---+ +---------+ +---+ +---+ |
* | initialize close |
* +-----------------------------------------+
* </pre