代码之家  ›  专栏  ›  技术社区  ›  Taranjit Kang

SetTimeout不更新视图

  •  2
  • Taranjit Kang  · 技术社区  · 8 年前

    我的组件有一段代码,例如:

    this.test= false;
    setTimeout(() => {
        this.test= true;
    }, 1000);
    

    我的视图有{{test}}问题是视图永远不会变为true,而是保持为false。我读到这可能是一个与polyfills相关的问题?但它是为另一个项目工作的,我没有为此添加多填充。

    使现代化

    已修复,这是因为即使值为,也没有更新视图。我相信changedetectref是有道理的,但我决定将我的布尔值转换为可观察值,结果成功了。

    3 回复  |  直到 5 年前
        1
  •  1
  •   niry    8 年前

    您的问题很可能出现在代码的其他地方。您的示例代码有效 如果 封闭函数是一个function(),而不是arrow函数。否则,您将更新不同的 this . 关于什么时候 是可以访问的,我希望blow示例可以清楚地说明这一点。箭头函数没有 但是,箭头功能可以访问 从封闭函数。

    'use strict';
    
    let o = function(){};
    
    o.method = function() {
      let updateView = _=> {
        document.getElementById('app').append(this.test+'\n');
        this.test = "Test didn't work. (most likely unbounded)";
      } 
      this.test = 'Initial value';
      updateView();
      let i = 0;
      setTimeout(() => {
          this.test = 'Arrow function inside function() works';
          updateView()
        }, ++i * 1000);
      setTimeout(function() {
          this.test = 'Unbouned function() inside function() does not work';
          updateView();
        }, ++i * 1000);
      setTimeout(function() {
          this.test = 'Bouned function() inside function() works';
          updateView()
        }.bind(this), ++i * 1000);
    }
    
    o.method();
    <pre id="app"></pre>
        2
  •  0
  •   Ali Adravi    8 年前

    您的代码看起来不错,但不确定浏览器是否支持箭头功能,请尝试以下操作:

    setTimeout(function (){
       this.test= true;
    }, 1000);
    
        3
  •  0
  •   Chandru    8 年前

    尝试以下操作:

    组成部分ts

    import { Observable } from 'rxjs/Rx';
    
    export class sampleComponent {
        private test: boolean = false;
    
        constructor() {
            Observable.interval(1000).subscribe((x) => {
                this.test = true;
            });
        }    
    }
    

    组成部分html

    <div>{{test}}</div>
    

    demo

    推荐文章