React和Vue中监听变量变化的方法

2020-06-14 06:31:45易采站长站整理

null !== root &&
(!isWorking &&
0 !== nextRenderExpirationTime &&
expirationTime < nextRenderExpirationTime &&
((interruptedBy = fiber), resetStack()),
markPendingPriorityLevel(root, expirationTime),
(isWorking && !isCommitting$1 && nextRoot === root) ||
requestWork(root, root.expirationTime),
nestedUpdateCount > NESTED_UPDATE_LIMIT &&
((nestedUpdateCount = 0), reactProdInvariant("185")));
}
function requestWork(root, expirationTime) {
// 将需要渲染的root进行记录
addRootToSchedule(root, expirationTime);
if (isRendering) {
// Prevent reentrancy. Remaining work will be scheduled at the end of
// the currently rendering batch.
return;
}

if (isBatchingUpdates) {
// Flush work at the end of the batch.
if (isUnbatchingUpdates) {
// ...unless we're inside unbatchedUpdates, in which case we should
// flush it now.
nextFlushedRoot = root;
nextFlushedExpirationTime = Sync;
performWorkOnRoot(root, Sync, true);
}
// 执行到这边直接return,此时setState()这个过程已经结束
return;
}

// TODO: Get rid of Sync and use current time?
if (expirationTime === Sync) {
performSyncWork();
} else {
scheduleCallbackWithExpirationTime(root, expirationTime);
}
}

太过复杂,一些方法其实还没有看懂,但是根据断点可以把执行顺序先理一下,在 setState 之后会执行 performSyncWork ,随后是如下的一个执行顺序


performSyncWork => performWorkOnRoot => renderRoot => workLoop => performUnitOfWork => beginWork => applyDerivedStateFromProps

最终方法是执行


function applyDerivedStateFromProps(
workInProgress,
ctor,
getDerivedStateFromProps,
nextProps
) {
var prevState = workInProgress.memoizedState;
{
if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
// Invoke the function an extra time to help detect side-effects.
getDerivedStateFromProps(nextProps, prevState);
}
}
// 获取改变的state
var partialState = getDerivedStateFromProps(nextProps, prevState);
{
// 对一些错误格式进行警告
warnOnUndefinedDerivedState(ctor, partialState);
} // Merge the partial state and the previous state.
// 判断getDerivedStateFromProps返回的格式是否为空,如果不为空则将由原的state和它的返回值合并
var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
// 设置state
// 一旦更新队列为空,将派生状态保留在基础状态当中
workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the