Component.js 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import {
  2. reRender
  3. } from './may-dom/MayDom';
  4. import {
  5. mergeState
  6. } from './util';
  7. import {
  8. mayQueue
  9. } from './may-dom/scheduler';
  10. export function Component(props, context, key, ref) {
  11. this.props = props;
  12. this.key = key;
  13. this.ref = ref;
  14. this.context = context;
  15. //新建个对象存放各种信息
  16. this.mayInst = {};
  17. }
  18. Component.prototype.setState = function (state, callback) {
  19. var lifeState = this.mayInst.lifeState;
  20. if (callback) {
  21. //回调队列调用之前也许sort
  22. callback = callback.bind(this);
  23. callback._mountOrder = this.mayInst.mountOrder;
  24. mayQueue.callbackQueue.push(callback);
  25. }
  26. if (this.mayInst.mergeStateQueue) {
  27. this.mayInst.mergeStateQueue.push(state);
  28. } else {
  29. this.mayInst.mergeStateQueue = new Array(state);
  30. }
  31. if (mayQueue.isInEvent) {
  32. //如果在绑定事件中 触发setState合并state
  33. if (mayQueue.dirtyComponentsQueue.indexOf(this) === -1) {
  34. this.mayInst.dirty = true;
  35. mayQueue.dirtyComponentsQueue.push(this);
  36. }
  37. return;
  38. }
  39. switch (lifeState) {
  40. //componentWillReceiveProps触发setState会合并state
  41. case 1: //componentWillMount 触发setState会合并state
  42. return;
  43. //ComponentWillReceiveProps 中setState 3
  44. //子组件在ComponentWillMount中调用父组件的setState 3
  45. case 3:
  46. case 2: //componentDidMount 触发setState会放到下一周期 2
  47. if (mayQueue.dirtyComponentsQueue.indexOf(this) === -1) {
  48. this.mayInst.dirty = true;
  49. this.mayInst.needNextRender = true; //子组件componentWillReceiveProps 调用父组件的setState 触发setState会放到下一周期
  50. mayQueue.dirtyComponentsQueue.push(this);
  51. }
  52. return;
  53. default:
  54. if (mayQueue.dirtyComponentsQueue.indexOf(this) === -1) {
  55. this.mayInst.dirty = true;
  56. mayQueue.dirtyComponentsQueue.push(this);
  57. }
  58. break;
  59. }
  60. mayQueue.clearQueue();
  61. }
  62. Component.prototype.forceUpdate = function (callback) {
  63. if (callback) {
  64. mayQueue.callbackQueue.push(callback.bind(this));
  65. }
  66. if (mayQueue.dirtyComponentsQueue.indexOf(this) === -1) {
  67. this.mayInst.forceUpdate = true;
  68. this.mayInst.dirty = true;
  69. mayQueue.dirtyComponentsQueue.push(this);
  70. }
  71. var lifeState = this.mayInst.lifeState;
  72. switch (lifeState) {
  73. case 1: //ComponentWillMount
  74. case 2: //componentDidMount
  75. case 3: //ComponentWillReceiveProps
  76. case 4: //ComponentWillReceiveProps
  77. return;
  78. default:
  79. mayQueue.clearQueue();
  80. break;
  81. }
  82. }
  83. Component.prototype.isMounted = function () {
  84. return this.mayInst ? (!!(this.mayInst.rendered && this.mayInst.rendered.mayInfo.hostNode) || this.mayInst.isEmpty) : false;
  85. }