The code from react-measure takes advantage of the new MutationObservers present in current browsers. MSDN has this to say about it:
Additionally, mutation observers are designed to record multiple changes before notifying your observer. They batch mutation records to avoid spamming your app with events. By contrast, mutation events are synchronous and interrupt normal code execution to notify your app of mutations. Despite the delayed notification model employed by mutation observers, your apps's observer is still guaranteed to receive (and have a chance to process) all the mutation records before the next repaint.
A react-measure's MutationObserver gets an array of MutationRecords, but the example code just grabs the first one:
<Measure
whitelist={['height']}
shouldMeasure={(mutations) => {
// don't update unless we have mutations available
if(mutations) {
return mutations[0].target
} else {
return false
}
}}
// notice how target gets passed into onMeasure now
onMeasure={(dimensions, mutations, target) => {
this.setState({dimensions})
}}
>
<div>
I can do cool things with my dimensions now :D
</div>
</Measure>
Sadly the readme doesn't have anything to say about why this works, and neither do MDN or MSDN. How do I know which MutationRecord to pass on?
In the spec, section 4.3.2 Queuing a mutation record, step 4.8:
Append record to observer’s record queue.
Then, if you search the spec for "queue a mutation record", you will see every action that can initiate the "queue a mutation record" algorithm.
From this you can tell that, for example, if you remove a node from the DOM, a mutation record will be queued (appended to the MutationRecords list).
Therefore, i believe it is safe to infer that MutationRecords are in the order in which they happened.
(You can easily do a test to verify this, add and remove some nodes synchronously, then inspect the MutationRecord)
来源:https://stackoverflow.com/questions/35900620/what-is-the-order-of-mutationrecords-received-by-mutationobservers