是否有任何简单的方法可以仅从 JavaScript 制作“componentDidUpdate()”生命周期方法?

问题描述

我想从 JavaScript 头开始创建我自己的 componentDidUpdate() 生命周期方法。 React 是如何做到的? Vue.JS 是如何制作自己的生命周期方法的。我尝试研究 Vue.JS 缩小版,但它让我很困惑。如果可以请告诉我,谢谢。类似于下面的内容

Element.prototype.whenUpdated = function() {
  /*some codes here that runs when the HTML element is updated*/
}

解决方法

componentDidUpdate 仅在视图框架的上下文中是可能的(并且只有真正有意义),其中元素的状态保存在框架内,并且视图的更改源于框架的更改状态。对框架状态的更改通过框架方法公开。

这里有一个小例子,说明类似的东西可能是什么样子:

// Framework code
class CustomDiv {
  constructor(sel,text) {
    this.container = document.querySelector(sel);
    this.text = text;
    this.update();
  }
  setText(newText) {
    this.text = newText;
    this.update();
  }
  update() {
    this.container.textContent = this.text;
    this.updateCallback?.();
  }
}

// Interact with the framework...
const customDiv = new CustomDiv('.container','initial text');
customDiv.updateCallback = () => {
  console.log('updated!');
};
setTimeout(() => {
  customDiv.setText('new text');
},1000);
<div class="container"></div>

虽然确实存在 MutationObserver,它可以观察 native 元素的内容和属性等的变化,但这是完全不同的事情。