{"id":22903499,"url":"https://github.com/sawyerbutton/detection-in-angular-react","last_synced_at":"2025-04-01T07:23:36.333Z","repository":{"id":120749130,"uuid":"153033467","full_name":"sawyerbutton/Detection-In-Angular-React","owner":"sawyerbutton","description":null,"archived":false,"fork":false,"pushed_at":"2018-10-15T03:51:13.000Z","size":63,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-02-07T04:40:58.177Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sawyerbutton.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-10-15T00:53:25.000Z","updated_at":"2018-10-15T03:50:51.000Z","dependencies_parsed_at":"2023-07-07T23:06:00.703Z","dependency_job_id":null,"html_url":"https://github.com/sawyerbutton/Detection-In-Angular-React","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sawyerbutton%2FDetection-In-Angular-React","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sawyerbutton%2FDetection-In-Angular-React/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sawyerbutton%2FDetection-In-Angular-React/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sawyerbutton%2FDetection-In-Angular-React/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sawyerbutton","download_url":"https://codeload.github.com/sawyerbutton/Detection-In-Angular-React/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246599000,"owners_count":20803120,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-12-14T02:37:26.967Z","updated_at":"2025-04-01T07:23:36.327Z","avatar_url":"https://github.com/sawyerbutton.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Detection-In-Angular-React\n\n## Angular和React中的变更检测\n\n### _感知变更惟一的方法是随之起舞_\n\n\u003e 变更检测机制存在于任何一个web应用中,并是大部分流行web框架中的重要组成部分\n\n\u003e 可能在开发应用时变更检测机制并没有展示在代码上,但是事实上变更检测潜伏在应用的某个位置\n\n\u003e 个人认为变更检测是架构中最重要的部分,因为它负责DOM更新等可见的部分\n\n\u003e 每一个有抱负的架构师都应该对这个机制有着良好的理解,因为变更检测显著地影响了应用程序的表现\n\n\u003e 本文中首先会介绍变化检测,然后将实现一个非常基本的变化检测机制,一旦明确了变化检测的本质,将深入了解它在Angular和React中的实现方式\n\n### 什么是变更检测\n\n\u003e 变更检测是用于跟踪应用程序状态并将更新的状态渲染到屏幕上的一种机制,这种机制将会确保用户界面始终与程序的内部状态保持同步\n\n\u003e 亦即变更检测存在两个重要的部分\n\n- 跟踪变更\n- 渲染变更\n\n### 渲染\n\n\u003e 在一个应用中,渲染的过程是获取程序的内部状态并将其投影到屏幕上的过程\n\n\u003e 在Web开发中采用对象和数组之类的数据结构并最终以图像,按钮和其他可视元素的形式呈现该数据的DOM表示\n\n\u003e 虽然有些时候渲染的逻辑可能并不是直截了当,但是大多数时候渲染还是很直白的\n\n\u003e 但是当数据随着时间发生变化后事情逐渐开始变得复杂起来了\n\n- 如今的Web应用程序是交互式的,这意味着应用程序状态可以随着用户的交互而随时更改\n- 也可能是因为后端服务的数据发生了变化,而前端作为客户端获取了这些更新\n- 当状态发生改变时,检测和反映出这些改变就非常有必要了\n\n#### 说明太抽象,例子来帮忙\n\n\u003e 假设想要实现一个评级部件,屏幕上的实心数反映了当前的评级\n\n\u003e 此交互式窗口部件允许用户单击任何星形并设置新的评级\n\n![rating widget](./assets/1.gif)\n\n\u003e 为了跟踪评级的状态需要将当前的值存储在应用的某处\n\n\u003e 为此定义私有属性`_rating`作为评级的状态\n\n```javascript\nexport class RatingsComponent {\n    constructor() {\n        this._rating = 1;\n    }\n}\n```\n \n\u003e 当更新部件的状态时需要在屏幕上反映这些更改,期待的DOM结构为\n\n```html\n\u003cul class=\"ratings\"\u003e\n    \u003cli class=\"star solid\"\u003e\u003c/li\u003e\n    \u003cli class=\"star solid\"\u003e\u003c/li\u003e\n    \u003cli class=\"star solid\"\u003e\u003c/li\u003e\n    \u003cli class=\"star outline\"\u003e\u003c/li\u003e\n    \u003cli class=\"star outline\"\u003e\u003c/li\u003e\n\u003c/ul\u003e\n```\n\n\u003e 使用CSS类solid和outline来渲染相应的星形图标,窗口部件初始化为所有列表项作为星形外轮廓而随着状态的改变,相应的列表项变为实心星形的样式\n\n\u003e 在部件初始化的过程中,我们需要创造所有需要的DOM节点\n\n```javascript\nexport class RatingsComponent {\n    //...\n    // container is a Dom node\n    init(container) {\n        this.list = document.createElement('ul');\n        this.list.classList.add('ratings');\n        this.list.addEventListener('click', (event) =\u003e {\n            this.rating = event.target.dataset.value;\n        });\n\n        this.elements = [1, 2, 3, 4, 5].map((value) =\u003e {\n            const li = document.createElement('li');\n            li.classList.add('star', 'outline');\n            li.dataset.value = value;\n            this.list.appendChild(li);\n            return li;\n        });\n\n        container.appendChild(this.list);\n    }\n}\n```\n\n\u003e 上述代码中创建了一个包含个体的无序列表。然后我们将CSS类添加到列表项上并为之创建`click`事件的监听器\n\n##### 触发变更检测\n\n\u003e 为了实现变更检测,当rating属性的值发生变化,应用程序应当接收到通知\n\n\u003e 在此使用Javascrpt的`setter`属性实现变更检测的流程\n\n\u003e 为rating属性定义一个`setter`,并在其值发生变化时触发更新方法,通过交换列表项上的CSS类来执行DOM更新\n\n```javascript\nexport class RatingsComponent {\n    //...\n    set rating(v) {\n        this._rating = v;\n\n        // 触发DOM更新方法\n        this.updateRatings();\n    }\n\n    get rating() {\n        return this._rating;\n    }\n\n    updateRatings() {\n        this.elements.forEach((element, index) =\u003e {\n            // 交换列表项的CSS类\n            element.classList.toggle('solid', this.rating \u003e index);\n            element.classList.toggle('outline', this.rating \u003c= index);\n        });\n    }\n}\n```\n\n[sample code](./basic-example/index.js)\n\n\u003e 截止到目前为止可能为了实现变更检测所付出的代码量还是可以接受的,但当遇到更复杂的功能`有多个列表和条件逻辑来显示或隐藏一些视觉元素`,代码量和复杂性将急剧增长,这是不可接受的状况\n\n\u003e 理想情况下,在日常开发中开发者希望专注于应用程序逻辑而不是重复地撰写类似的代码\n\n\u003e 应该有一个`其他东西`处理状态跟踪和屏幕更新的部分,而`框架就是这个其他东西`\n\n### 框架\n\n\u003e 框架负责应用程序的内部状态和用户界面之间的同步,有效地进行状态跟踪和DOM更新\n\n\u003e 下述是在Angular和React中实现相同的部件的模板,从用户对UI的角度来看,模板是组件配置中最重要的部分\n\n- Angular\n\n```html\n\u003cul class=\"rating\" (click)=\"handleClick($event)\"\u003e\n    \u003cli [className]=\"'star ' + (rating \u003e 0 ? 'solid' : 'outline')\"\u003e\u003c/li\u003e\n    \u003cli [className]=\"'star ' + (rating \u003e 1 ? 'solid' : 'outline')\"\u003e\u003c/li\u003e\n    \u003cli [className]=\"'star ' + (rating \u003e 2 ? 'solid' : 'outline')\"\u003e\u003c/li\u003e\n    \u003cli [className]=\"'star ' + (rating \u003e 3 ? 'solid' : 'outline')\"\u003e\u003c/li\u003e\n    \u003cli [className]=\"'star ' + (rating \u003e 4 ? 'solid' : 'outline')\"\u003e\u003c/li\u003e\n\u003c/ul\u003e\n```\n\n- React\n\n```jsx\n\u003cul className=\"rating\" onClick={handleClick}\u003e\n    \u003cli className={'star ' + (rating \u003e 0 ? 'solid' : 'outline')}\u003e\u003c/li\u003e\n    \u003cli className={'star ' + (rating \u003e 1 ? 'solid' : 'outline')}\u003e\u003c/li\u003e\n    \u003cli className={'star ' + (rating \u003e 2 ? 'solid' : 'outline')}\u003e\u003c/li\u003e\n    \u003cli className={'star ' + (rating \u003e 3 ? 'solid' : 'outline')}\u003e\u003c/li\u003e\n    \u003cli className={'star ' + (rating \u003e 4 ? 'solid' : 'outline')}\u003e\u003c/li\u003e\n\u003c/ul\u003e\n```\n\n\u003e 虽然上述模板\b有些细微的差异,但是`使用表达式作为DOM元素属性的值`的理念是相同的\n\n\u003e 上述代码中,DOM属性`className`取决于组件的`rating`属性,当`rating`属性发生变化时,表达式都会重新计算\n\n\u003e 亦即,如果变更被检测到了,`className`属性将会被更新\n\n\u003e 值得注意的是,事件监听器并不是React或Angular中的变更检测的一部分,事件监听通常会触发变更检测,但其本身不是过程一部分\n\n### 变更检测在框架中的应用\n\n\u003e 虽然`使用表达式作为DOM元素属性值`的想法在Angular和React中都是相同的,但二者的底层机制却完全不同\n\n#### 对于Angular而言\n\n\u003e 当编译器分析模板时,首先会标识与DOM元素相关联的组件的属性,并对于每个这样的关联,编译器以指示(instructions)的形式创建绑定\n\n\u003e 绑定是Angular变更检测中的核心部分,它定义了组件属性`通常包含在某个表达式中`与DOM元素属性之间的关联\n\n\u003e 一旦创建了绑定ngular就不作用于于模板,`变更检测机制执行处理绑定的指令`,这些指令的作用是检查`具有组件属性的表达式的值`是否已更改,并在必要时执行DOM更新\n\n\u003e 上述的例子中模板的`rating属性`通过表达式绑定到`className属性`\n\n```\n[className]=\"'star ' + ((ctx.rating \u003e 0) ? 'solid' : 'outline')\"\n```\n\n\u003e 对于模板的这一部分编译器生成用于`设置绑定`,`执行脏检查`和`更新DOM`的指示,比如:\n\n```typescript\nif (initialization) {\n    elementStart(0, 'ul');\n        ...\n        elementStart(1, 'li', ...);\n\n        // 给className属性设置绑定\n        elementStyling();\n        elementEnd();\n        ...\n    elementEnd();\n}\n\nif (changeDetection) {\n\n    // 检查表达式的值是否发生了改变\n    // 如果表达式的值发生了改变则将绑定设定为污染并更新dom\n    elementStylingMap(1, ('star ' + ((ctx.rating \u003e 0) ? 'solid' : 'outline')));\n    elementStylingApply(1);\n    ...\n}\n```\n\n\u003e 值得注意的是,上述代码中的绑定指示是基于`Ivy的新编译器`的输出,以前版本的Angular使用完全相同的绑定和脏检查的机制只是实现略有不同\n\n\u003e 假设Angular为className创建了绑定,绑定的当前值如下:\n\n```typescript\n{ dirty: false, value: 'outline' }\n```\n\n\u003e 当`rating`属性发生变更时,Angular会运行变更检测并处理指令\n\n\u003e 首先\b指令会获取计算表达式的结果,并使用它与绑定存储的先前值进行比较\n\n\u003e 这就是`脏检查`这个名称的来源 - 如果值已更改,则更新当前值并将此绑定标记为脏\n\n```typescript\n{ dirty: true, value: 'solid' }\n```\n\n\u003e 后续指令检查绑定是否为脏,如果是,则使用新值更新DOM,而在上述例子中,它将更新列表项的className属性\n\n##### _处理执行脏检查和更新DOM的相关部分的绑定是Angular中变更检测的核心操作_\n\n#### 对于React而言\n\n\u003e React使用截然不同的方式实现变更检测\n\n\u003e React中变更检测机制的核心部分是比较`Virtual DOM`\n\n\u003e 所有React组件都实现了`返回JSX模板`的`render方法`,并且模板被编译成\b`React.createElement`的函数调用\n\n```javascript\nconst el = React.createElement;\n\nexport class RatingComponent extends ReactComponent {\n    //...\n    render() {\n        return el('ul', { className: 'ratings', onclick: handleClick}, [\n                 el('li', { className: 'star ' + (rating \u003e 0 ? 'solid' : 'outline') }),\n                    ...\n        ]);\n    }\n}\n```\n\n\u003e 每一个`React.createElement`函数都创建一个名为`Virtual DOM节点`的数据结构\n\n\u003e 事实上这个部分没有什么特别只是一个简单的JavaScript对象描述了`一个HTML元素及其属性和子元素`\n\n\u003e 但是当多次调用`React.createElement`函数后,它们共同创建了一个`Virtual DOM树`\n\n```javascript\nexport class RatingComponent extends ReactComponent {\n    ...\n    render() {\n        return {\n            tagName: 'UL',\n            properties: {className: 'ratings'},\n            children: [\n                {tagName: 'LI', properties: {className: 'outline'}},\n                ...\n            ]\n        }\n    }\n}\n```\n\n\u003e 具有组件属性的表达式将会在`render`方法被调用时重新计算评估,而`Virtual DOM节点属性`包含已计算表达式的结果\n\n\u003e 假设在上述的例子中,`rating属性`的值为0.这意味着:\n\n```javascript\n{ className: rating \u003e 0 ? 'solid' : 'outline' }\n```\n\n\u003e 计算结果为`outline`并作为`Virtual Dom`中`className`属性的值\n\n\u003e 基于当前的`Virtual Dom`树,React\b将会创建拥有CSS类为`outline`的列表元素\n\n\u003e 现在`rating`属性更新为1,则表达式为将会\b修改`className`属性为`solid`,此时React运行变更检测,执行`render`方法执行返回一个新的`Virtul Dom`树(`className`属性为`solid`)\n\n\u003e 需要注意的是,在每个\b变更检测周期中`render`方法都会被调用,这意味着每次调用该函数时,它都能返回完全不同的Virtual DOM树\n\n\u003e 所以现在有两个Virtual DOM数据结构,之后在两个`Virtual DOM`上运行区分算法,以获取它们之间的一组更改\n\n[virtual dom](./assets/2.png)\n\n\u003e 一旦找到差异,算法就会生成一个补丁来更新相应的DOM节点\n\n\u003e 在示例中,补丁将使用新`Virtual DOM`中的`solid`值更新`className属性`, 之后这个更新版本的`Virtual DOM`将用于下一个变更检测周期的比较\n\n##### 总结\n\n`从组件中获取新的Virtual DOM树,将其与Virtual Dom树的先前版本进行比较,生成修补以更新DOM的相关部分并执行更新是React中变更检测的核心操作`\n\n#### 变更检测的执行时间点\n\n\u003e 为了深入理解变更检测,还需要知晓何时`React执行render方法`和`Angular执行处理绑定的指令`\n\n\u003e 按照逻辑而言,一般有两种方式触发变更检测\n\n1. 明确告诉框架某些`事情,属性,对象`发生了变化,或者`有可能发生变化`,因此它应该运行变更检测\n2. 依靠框架来知晓何时有可能发生变化并`自动运行变更检测`\n\n##### React只有一种方式\n\n\u003e 在React中总是通过调用`setState函数`手动初始化变更检测过程,没有自动触发变更检测的方式\n\n```javascript\nexport class RatingComponent extends React.Component {\n    //...\n    handleClick(event) {\n        this.setState({rating: Number(event.target.dataset.value)})\n    };\n}\n```\n\n\u003e 每个变更检测周期都从调用`setState函数`开始\n\u003e 值得注意的是，`setState函数`是一个请求也可以理解为一个异步函数，它并不会立刻更新组件\n\u003e 在React中，为了效率等原因可能会延迟这个过程在后续的`VM turn`中执行之\n\n##### 在Angular中拥有两种方式\n\n\u003e 可以使用`Change Detector service`手动执行变更检测\n\n```typescript\nclass RatingWidget {\n    constructor(private cd: changeDetector) {\n    }\n\n    handleClick(event) {\n        this.rating = Number(event.target.dataset.value);\n        this.cd.detectChanges();\n    };\n}\n```\n\n\u003e 也可以依靠框架自动触发变化检测\n\n```typescript\nclass RatingWidget {\n    handleClick(event) {\n        this.rating = Number(event.target.dataset.value);\n    };\n}\n```\n\n\u003e 但是也有随之而来的疑问,Angular作为框架如何知晓何时执行变更检测\n\n1. 使用Angular提供的绑定机制绑定模板中的UI事件用以知晓所有的UI事件监听器,这意味着它可以拦截事件侦听器并在应用程序代码完成执行后安排 变更检测运行\n2. 上述的拦截机制是一个很棒的理念但是并不能应用于所有的异步事件(比如setTimeout事件和XHR事件)\n3. 为了解决2中存在的缺陷,Angular使用`zone.js`库修补分配浏览器中的所有异步事件,确保可以在发生特定事件时通知Angular,实际效果与UI事件类似,Angular可以等到应用程序代码完成执行并自动启动变更检测\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsawyerbutton%2Fdetection-in-angular-react","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsawyerbutton%2Fdetection-in-angular-react","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsawyerbutton%2Fdetection-in-angular-react/lists"}