检查后表达式已更改.先前的值:'null:1561881140820'.当前值:'null:1568881140880' [英] Expression has changed after it was checked. Previous value: 'null: 1561881140820'. Current value: 'null: 1561881140880'

查看:70
本文介绍了检查后表达式已更改.先前的值:'null:1561881140820'.当前值:'null:1568881140880'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,有一个getter每次都返回新日期,我想根据该日期更新元素的样式.这是简单的示例:

In my app, there is a getter that returns new date everytime and I want to update the style of an element based on that date. Here is the simple example:

app.component.html

app.component.html

<h1>Gantt-Flexx</h1>
{{currentMillis}}

app.component.ts

app.component.ts

export class AppComponent{
    get currentMillis(){
        return new Date().getTime()
    }
}

这会触发此错误

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'null: 1561881140820'. Current value: 'null: 1561881140880'.
    at viewDebugError (core.js:17871)
    at expressionChangedAfterItHasBeenCheckedError (core.js:17859)
    at checkBindingNoChanges (core.js:18059)
    at checkNoChangesNodeInline (core.js:27635)
    at checkNoChangesNode (core.js:27624)
    at debugCheckNoChangesNode (core.js:28228)
    at debugCheckRenderNodeFn (core.js:28182)
    at Object.eval [as updateRenderer] (AppComponent.html:2)
    at Object.debugUpdateRenderer [as updateRenderer] (core.js:28171)
    at checkNoChangesView (core.js:27525)

推荐答案

之所以会这样,是因为您正在使用 {{currentMillis}} currentMillis 分配给角度表达式,所以每个更改检测周期都会触发此函数 get currentMillis().

This is happening because you are assigning currentMillis to angular expression using {{currentMillis}} , so this function get currentMillis() is triggered on every change detection cycle.

尝试将 console.log 放入该函数中,然后查看(确保不要将函数分配给 {{}} ,因为它会被不必要地调用并影响效果).因此,每次运行更改检测时,它都会获得不同的值,因为 time 每毫秒更改一次.

Try putting console.log in that function and see (Make sure you are never assigning a function to {{ }} because it would be called unnecessarily and impact the performance). So, every time Change detection runs, it gets different value because the time is changed every millisecond.

请引用 ChangeDetection视频来处理此确切问题及其发生原因

Refer ChangeDetection video to handle this exact problem and why it happening

这篇关于检查后表达式已更改.先前的值:'null:1561881140820'.当前值:'null:1568881140880'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆