-
Notifications
You must be signed in to change notification settings - Fork 2
/
react.development.js
2410 lines (2167 loc) · 91.9 KB
/
react.development.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @license React v16.8.6
* react.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var process = {
env: {
NODE_ENV: 'dev'
}
};
if (process.env.NODE_ENV !== "production") {
(function() {
'use strict';
var _assign = require('object-assign');
var checkPropTypes = require('prop-types/checkPropTypes');
// TODO: this is special because it gets imported during build.
var ReactVersion = '16.8.6';
// 使用Symbol来标记类似react的属性,如果没有原生的Symbol或腻子语法,使用一个数字来标记
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
// Symbol.for 以字符串为key,创建symbol,如果以前有,使用以前的,否则新建一个
// 这些都是react内部的api,不清楚的可以官网去查
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
// 懒加载标记
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
// 定义symbol,如果不支持的话会用兜底方案
// 返回symbol的迭代器
var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
// 属性的key
// 要成为可迭代对象,一个对象必须实现@@iterator方法,这意味着对象 必须有一个键为@@iterator属性,可通过常量Symbol.iterator访问该属性
// https://www.cnblogs.com/pengsn/p/12892954.html
var FAUX_ITERATOR_SYMBOL = '@@iterator';
// 返回迭代器的函数
function getIteratorFn(maybeIterable) {
if (maybeIterable === null || typeof maybeIterable !== 'object') {
return null;
}
// 获取传入参数的iterator或者@@iterator
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
if (typeof maybeIterator === 'function') {
return maybeIterator;
}
return null;
}
// 使用invariant来判断入参的不变性
// 使用类似sprintf的格式来处理入参,相关信息会被移除,但是函数本身在生产环境会被保留
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
// 验证格式
var validateFormat = function () {};
{
// 处理错误信息需要格式,没有格式的话抛错,格式可以理解为一个字符串模板
validateFormat = function (format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error = void 0;
if (format === undefined) {
// 如果没有格式,抛出非格式化的错误
// 压缩后的代码有抛错发生,请使用非压缩的开发模式,以便获取完整的报错信息
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
// replace方法会对每一个匹配项返回回调函数的返回值
// 生成错误提示
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
// 报错的名字是不变性的破坏
error.name = 'Invariant Violation';
}
// 我们并不care 报错函数本身的调用栈,位置置为1,frame这里可以理解为调用栈中的某一帧
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
// 依靠对invariant的实现,我们可以保持格式和参数在web的构建中
// Relying on the `invariant()` implementation lets us
// preserve the format and params in the www builds.
// 这里的warning实现是从fbjs/warning forked来的
// 唯一的不同时我们使用console.warn而不是console.error,当没有原生console实现是我们啥也不做,这就是简化后的代码
// 这个和invariant十分类似,唯一的不同是在条件不满足时我们将打印warning
// 这个可以在开发环境中打印报错的绝对路径。在生产环境下移除log代码将会保持同样的逻辑并且维持同样的代码路径
/**
* Forked from fbjs/warning:
* https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
*
* Only change is we use console.warn instead of console.error,
* and do nothing when 'console' is not supported.
* This really simplifies the code.
* ---
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
// 低优先级的告警
var lowPriorityWarning = function () {};
// 这个括号为了封闭上下文,保持干净的命名空间?(哪位高人可以解答下,请留言)
// 大括号里面可以避免被覆盖?
{
var printWarning = function (format) {
// 复制入参数组
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
// 拼凑信息
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
// 如果有console的实现使用它
if (typeof console !== 'undefined') {
console.warn(message);
}
// 啥也没做
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
// 方便使用调用栈查询
// 调试react用的
throw new Error(message);
} catch (x) {}
};
lowPriorityWarning = function (condition, format) {
// 没有格式信息,抛错
if (format === undefined) {
throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (!condition) {
// 首先复制数组
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
// 传入格式和参数
printWarning.apply(undefined, [format].concat(args));
}
};
}
var lowPriorityWarning$1 = lowPriorityWarning;
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
// 无调用栈的警告
var warningWithoutStack = function () {};
{
warningWithoutStack = function (condition, format) {
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
if (format === undefined) {
// 没有格式直接报错
throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (args.length > 8) {
// Check before the condition to catch violations early.
throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
}
// 如果true直接忽略
if (condition) {
return;
}
if (typeof console !== 'undefined') {
// 将所有入参转换成字符串
var argsWithFormat = args.map(function (item) {
return '' + item;
});
// 添加warning头
argsWithFormat.unshift('Warning: ' + format);
// We intentionally don't use spread (or .apply) directly because it
// breaks IE9: https://github.com/facebook/react/issues/13610
// 不直接调用call,因为在ie9下会报错
// 手动抛出warning
// console方法会自动替换%s, 使用添加的后续参数
// 这个用法看不懂的,看看这篇https://www.cnblogs.com/web-record/p/10477778.html
Function.prototype.apply.call(console.error, console, argsWithFormat);
}
try {
// 这里是给react调试的地方,正常情况下是不会有作用的
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
// 手动抛出错误
throw new Error(message);
} catch (x) {}
};
}
// warning函数的副本
var warningWithoutStack$1 = warningWithoutStack;
// 未挂载组件的警告状态的是否更新
// 一个map,key是组件内部方法的名字
var didWarnStateUpdateForUnmountedComponent = {};
// no-op的警告 no-operate
function warnNoop(publicInstance, callerName) {
{
var _constructor = publicInstance.constructor;
// 获取组件的名字
var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
// 告警的key
var warningKey = componentName + '.' + callerName;
// 是否更新过
if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
return;
}
// 调用抛出错误的方法,同时登记,避免二次触发
// 不能在一个未挂载的组件上调用某个方法,这个是无意义的操作,
// 但是这会触发你应用中的bug,为此你可以在组件中直接指向this.state或者定义state对象,在某个组件中带有所需状态的类属性。
warningWithoutStack$1(false, "Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);
didWarnStateUpdateForUnmountedComponent[warningKey] = true;
}
}
/**
* This is the abstract API for an update queue.
*/
// 更新no-op队列的抽象api,no-operate的队列
var ReactNoopUpdateQueue = {
// 检查这个复合组件是否挂载
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
// 入参是组件实例
isMounted: function (publicInstance) {
return false;
},
// 强制刷新,前提是不能在dom 变更的过程中更新
// 你可能会想在某些无法使用setState更新状态的情况下强制刷新状态,
// forceUpdate无法触发shouldComponentUpdate,但是会触发componentWillUpdate和componentDidUpdate
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/
// 队列空调用的警告
enqueueForceUpdate: function (publicInstance, callback, callerName) {
warnNoop(publicInstance, 'forceUpdate');
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/
// 更新所有的状态,始终使用这个或者setState来改变状态,应该把this.state当作不可变的
enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
warnNoop(publicInstance, 'replaceState');
},
// 设置状态的子集,这个提供merge策略,不支持深度复制,下一阶段:暴露pendingState或者在合并阶段不使用
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after component is updated.
* @param {?string} Name of the calling function in the public API.
* @internal
*/
enqueueSetState: function (publicInstance, partialState, callback, callerName) {
warnNoop(publicInstance, 'setState');
}
};
// 定义空对象
var emptyObject = {};
// 冻起来
{
Object.freeze(emptyObject);
}
/**
* Base class helpers for the updating state of a component.
*/
// 组件的构造函数
function Component(props, context, updater) {
this.props = props;
this.context = context;
// 如果组件使用字符串的refs,我们将会指定一个不同的对象
// If a component has string refs, we will assign a different object later.
this.refs = emptyObject;
// 初始化默认的更新器,真实的更新器将会在渲染器内注入
// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
// 定义原型属性
Component.prototype.isReactComponent = {};
// 设置状态的子集,始终使用this去改变状态,需要把this.sate当成正常状态下不可变的
// 并不保证this.state会马上更新,先设置再取值可能返回的是老值
// 并不保证setState的调用是同步的,因为多个调用最终会被合并,你可以提供一个可选的回调,在setStates事实上完成之后调用
// 当一个函数传递给setState时,它将在未来的某个时间点被调用,并且使用最新的参数(state,props,context等)这心值可能跟this.xxx不一样
// 因为你的函数是在receiveProps之后,shouldComponentUpdate之前调用的,在这个新阶段,props和context并没有赋值给this
/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
Component.prototype.setState = function (partialState, callback) {
// void 0 === undefined 省字节,同时防止undefined被注入
// partialState需要是对象,函数或者null
!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : void 0;
// 进入队列状态更新
this.updater.enqueueSetState(this, partialState, callback, 'setState');
};
// 强制刷新,该方法只能在非DOM转化态的时候调用
// 在一些深层状态改变但是setState没有被调用的时候使用,该方法不会调用shouldComponentUpdate,但componentWillUpdate和componentDidUpdate会被调用
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
Component.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};
// 废弃的api,这些api只会在经典的类组件上存在,我们将会遗弃它们。我们并不会直接移除他们,而是定义getter,并抛错
/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
{
var deprecatedAPIs = {
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
};
// 定义遗弃api的告警函数
var defineDeprecationWarning = function (methodName, info) {
Object.defineProperty(Component.prototype, methodName, {
get: function () {
lowPriorityWarning$1(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
return undefined;
}
});
};
// 依次注入getter
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
// 假组件,原型是真组件的原型
function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;
/**
* Convenience component with default shallow equality check for sCU.
*/
// 一个方便的组件,默认浅相等校验,其实是构造函数
function PureComponent(props, context, updater) {
this.props = props;
this.context = context;
// 如果有字符串类型的ref,我们将在稍后指派一个不同的对象
// If a component has string refs, we will assign a different object later.
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
}
// 关于原型和构造函数的相关内容可以参考https://blog.csdn.net/cc18868876837/article/details/81211729
// 纯粹的组件原型
var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
// 定义纯粹组件原型的构造函数
pureComponentPrototype.constructor = PureComponent;
// Avoid an extra prototype jump for these methods.
// 原型上再次注入Component的原型
_assign(pureComponentPrototype, Component.prototype);
// 标志位,判断是纯粹组件
pureComponentPrototype.isPureReactComponent = true;
// an immutable object with a single mutable value
// 一个不可变的对象,一个不可变的值
// 被封闭对象仍旧全等该对象本身
// 可以通过Object.isSealed来判断当前对象是否被封闭
// 不能为被封闭对象添加任何未知属性, 也不能为其已知属性添加访问者
// 可以修改已知的属性
// https://www.jianshu.com/p/96220f921272
function createRef() {
// 只有current一个属性
var refObject = {
current: null
};
{
Object.seal(refObject);
}
return refObject;
}
/**
* Keeps track of the current dispatcher.
*/
// 跟踪当前的分发者
var ReactCurrentDispatcher = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
// 跟踪react当前的所有者,指的是所有正在构造的组件的父组件
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
// 正则,匹配任意内容加正反斜杆
// 括号内的内容是分组 https://www.jianshu.com/p/f09508c14e65
// match如果是全局匹配,返回的是所有的匹配项,如果不是返回的是匹配字符串,位置,原始输入,如果有分组,第二项是匹配的分组
var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
// 描述组件的引用位置
var describeComponentFrame = function (name, source, ownerName) {
var sourceInfo = '';
if (source) {
var path = source.fileName;
// 解析出文件名
var fileName = path.replace(BEFORE_SLASH_RE, '');
{
// In DEV, include code for a common special case:
// prefer "folder/index.js" instead of just "index.js".
// 在开发环境下,如果文件名为index 输出带上一级路径的文件名
if (/^index\./.test(fileName)) {
// 解析出反斜杠前的文件名
var match = path.match(BEFORE_SLASH_RE);
if (match) {
var pathBeforeSlash = match[1];
if (pathBeforeSlash) {
// 获得文件名前的文件夹的名字
var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
fileName = folderName + '/' + fileName;
}
}
}
}
// 获取最近的文件夹名和文件名,拼上代码行数
sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
} else if (ownerName) {
sourceInfo = ' (created by ' + ownerName + ')';
}
return '\n in ' + (name || 'Unknown') + sourceInfo;
};
var Resolved = 1;
// 细化解析惰性组件
function refineResolvedLazyComponent(lazyComponent) {
// 如果已经resolved,返回结果
return lazyComponent._status === Resolved ? lazyComponent._result : null;
}
// 获取外层组件的名字
function getWrappedName(outerType, innerType, wrapperName) {
var functionName = innerType.displayName || innerType.name || '';
// 优先是outerType的displayName,否则是wrapperName和functionName的组合
return outerType.displayName || (functionName !== '' ? wrapperName + '(' + functionName + ')' : wrapperName);
}
// 获取组件名
function getComponentName(type) {
if (type == null) {
// Host root, text node or just invalid type.
// 如果是根,文字节点或不存在的类型,返回null
return null;
}
{
// 如果type的tag是数字
if (typeof type.tag === 'number') {
// 告警:接收到了预料之外的对象,这可能是react内部的bug,请提issue
warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
}
}
// 如果是构造函数,看他的静态属性displayName或者name
if (typeof type === 'function') {
return type.displayName || type.name || null;
}
// 如果是字符串直接返回
if (typeof type === 'string') {
return type;
}
switch (type) {
// 如果是react当前的节点,这些都是当初symbol定义的
case REACT_CONCURRENT_MODE_TYPE:
return 'ConcurrentMode';
case REACT_FRAGMENT_TYPE:
return 'Fragment';
// 如果是入口
case REACT_PORTAL_TYPE:
return 'Portal';
// 如果是分析器
case REACT_PROFILER_TYPE:
return 'Profiler';
case REACT_STRICT_MODE_TYPE:
return 'StrictMode';
case REACT_SUSPENSE_TYPE:
return 'Suspense';
}
// 如果type是对象
if (typeof type === 'object') {
// 按照$$typeof来判断
switch (type.$$typeof) {
case REACT_CONTEXT_TYPE:
return 'Context.Consumer';
case REACT_PROVIDER_TYPE:
return 'Context.Provider';
// 如果是前向ref
case REACT_FORWARD_REF_TYPE:
return getWrappedName(type, type.render, 'ForwardRef');
// 如果是memo类型,递归调用自己
case REACT_MEMO_TYPE:
return getComponentName(type.type);
// 如果是lazy类型
case REACT_LAZY_TYPE:
{
var thenable = type;
// 细化解析惰性组件
var resolvedThenable = refineResolvedLazyComponent(thenable);
if (resolvedThenable) {
return getComponentName(resolvedThenable);
}
}
}
}
// 最后返回null
return null;
}
// react正在debug的frame,可以理解为一个对象里面有一些方法可供调取当前组件的调用栈
var ReactDebugCurrentFrame = {};
// 当前正在验证的元素
var currentlyValidatingElement = null;
// 设置当前正在验证的元素
function setCurrentlyValidatingElement(element) {
{
currentlyValidatingElement = element;
}
}
{
// 堆栈的实现是通过当前的renderer注入的
// Stack implementation injected by the current renderer.
ReactDebugCurrentFrame.getCurrentStack = null;
// 增加枚举的方法
// 本质上是返回调用堆栈的附录
ReactDebugCurrentFrame.getStackAddendum = function () {
var stack = '';
// Add an extra top frame while an element is being validated
// 增加一个额外的顶层框架,如果当前有元素正在被验证
if (currentlyValidatingElement) {
// 获取元素的名字
var name = getComponentName(currentlyValidatingElement.type);
// 获取元素所有者
var owner = currentlyValidatingElement._owner;
// 获取源的目录位置
stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type));
}
// Delegate to the injected renderer-specific implementation
// 转交给renderer中的特殊实现来获取堆栈
// 如果getCurrentStack被复写,追加该方法提供的信息
var impl = ReactDebugCurrentFrame.getCurrentStack;
if (impl) {
stack += impl() || '';
}
return stack;
};
}
// react内部共享的控制构件
var ReactSharedInternals = {
// 当前的分发者
ReactCurrentDispatcher: ReactCurrentDispatcher,
// 当前的所有者
ReactCurrentOwner: ReactCurrentOwner,
// Object.assign避免在UMD下被打包两次
// Used by renderers to avoid bundling object-assign twice in UMD bundles:
assign: _assign
};
{
_assign(ReactSharedInternals, {
// 在生产环境不应该有
// These should not be included in production.
ReactDebugCurrentFrame: ReactDebugCurrentFrame,
// Shim for React DOM 16.0.0 which still destructured (but not used) this.
// TODO: remove in React 17.0.
// react树形钩子
ReactComponentTreeHook: {}
});
}
// 类似于不变性的警告,只有在条件不满足的时候才打印
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
// 首先赋值warningWithoutStack$1
var warning = warningWithoutStack$1;
// 本质上是带调用栈的warning方法
{
// 第二个条件是格式化
warning = function (condition, format) {
if (condition) {
return;
}
// 获取当前的调用序列
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
var stack = ReactDebugCurrentFrame.getStackAddendum();
// eslint-disable-next-line react-internal/warning-and-invariant-args
// 拼装后面的参数
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
// 复用原来的warning方法,前面的内容照旧,后面的内容拼上调用序列的信息
warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack]));
};
}
var warning$1 = warning;
// 定义hasOwnProperty方法
var hasOwnProperty = Object.prototype.hasOwnProperty;
// 属性保留字
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
// 特殊的属性key展示告警
// void 0 就是undefined
var specialPropKeyWarningShown = void 0;
var specialPropRefWarningShown = void 0;
// 排除ref是warning的情况,判断是否存在ref
function hasValidRef(config) {
{
// 如果config有ref自有属性属性
if (hasOwnProperty.call(config, 'ref')) {
// 获取get方法
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
// 如果这个getter是warning的,返回false
if (getter && getter.isReactWarning) {
return false;
}
}
}
// 否则根据是否undefined来判断
return config.ref !== undefined;
}
// 是否具有可用属性
// 逻辑跟ref的很相似
function hasValidKey(config) {
{
if (hasOwnProperty.call(config, 'key')) {
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.key !== undefined;
}
// 定义key属性的warning Getter
function defineKeyPropWarningGetter(props, displayName) {
// 关于访问key的告警
var warnAboutAccessingKey = function () {
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
// key不能作为参数获取,被react内部征用了
// key不能作为参数,尝试去获取它只会返回undefined,如果你想获取子组件上的这个值,你应该传另一个名字的属性
warningWithoutStack$1(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName);
}
};
// 这个函数定义为react warngin
warnAboutAccessingKey.isReactWarning = true;
// 给入参的key属性定义getter,避免外界访问
Object.defineProperty(props, 'key', {
get: warnAboutAccessingKey,
configurable: true
});
}
// 这部分内容跟key的非常类似
// 定义ref的获取方法
function defineRefPropWarningGetter(props, displayName) {
var warnAboutAccessingRef = function () {
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
warningWithoutStack$1(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName);
}
};
warnAboutAccessingRef.isReactWarning = true;
Object.defineProperty(props, 'ref', {
get: warnAboutAccessingRef,
configurable: true
});
}
// 定义一个创建react 元素的构造函数,这跟class模式的组建不一样,请不要使用new来调用,所有instanceof来检查是失效的,不要使用要用Symbol.for('react.element'),而要用$$typeof来检查,
// 来判断是否是react组件
// self是一个暂时的变量,是用来判断当React.createElement被调用的时候this和owner是否一致,以便我们告警。我们打算摆脱owner这个概念并且
// 使用箭头函数,只要这个二者一致,组件就没有变化
// source是一个注释对象(被转译器或者其他文件名,行数,等信息所添加)
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, no instanceof check
* will work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} key
* @param {string|object} ref
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @param {*} owner
* @param {*} props
* @internal
*/
// react元素构造函数
// 返回的其实是element对象
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// 通过这个标签来识别react的元素
// This tag allows us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// 属于这个元素的内建属性
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// 记录创建这个组件的组件
// Record the component responsible for creating this element.
_owner: owner
};
{
// 这个验证标志是可变的,我们把这个放在外部支持存储,以便我们能够冻结整个对象,
// 这个可以被若映射替代,一旦在开发环境下实现了
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {};
// 为了更加方便地进行测试,我们设置了一个不可枚举的验证标志位,以便测试框架忽略它
// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
// 给_store设置validated属性false
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
});
// self和source都是开发环境才存在的
// self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
});
// 两个再不同地方创建的元素从测试的角度来看是相等的,我们在列举的时候忽略他们
// Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
// 如果Object有freeze的实现,我们冻结元素和它的属性
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
};
// 创建并返回指定类型的reactElement
/**
* Create and return a new ReactElement of the given type.
* See https://reactjs.org/docs/react-api.html#createelement
*/
function createElement(type, config, children) {
// 属性名 void 0就是undefined
var propName = void 0;
// Reserved names are extracted
// 被保护的名字被屏蔽
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
// 根据confi的内容来初始化
if (config != null) {
// 如果有可用的ref,将其赋值给ref变量
if (hasValidRef(config)) {
ref = config.ref;
}
// 如果有可用的key,将其赋值给key
if (hasValidKey(config)) {
key = '' + config.key;
}
// 再给self赋值
self = config.__self === undefined ? null : config.__self;
// 给source赋值
source = config.__source === undefined ? null : config.__source;
// Remaining properties are added to a new props object
for (propName in config) {
// 如果不是保留字的话就复制属性
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
// 子元素会有不止一个,这些将会通过一个属性对象向下传递