【问题标题】:How to update a dynamic DOM value with particular interval?如何以特定间隔更新动态 DOM 值?
【发布时间】:2019-09-10 08:42:21
【问题描述】:

我需要使用每秒计时器来动态更新 DOM 值。

我尝试过每秒增加一次计数器值。但是在那个代码中,我只得到了那个 DOM 值的最终值。我需要 DOM 中的每一秒值。

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="StartLiveUpdate">Click me</button>

<button class="btn btn-primary" @onclick="StopLiveUpdate">Stop</button>

@code {


    private static System.Timers.Timer syncTimer;
    Random random = new Random();
    void StartLiveUpdate()
    {
        syncTimer = new System.Timers.Timer(1000);

        syncTimer.Elapsed += IncrementCount;
        syncTimer.AutoReset = true;
        syncTimer.Enabled = true;
    }
    void StopLiveUpdate()
    {
        syncTimer.Enabled = false;
        syncTimer.Stop();
    }
    int currentCount = 0;

    void IncrementCount(Object source, System.Timers.ElapsedEventArgs e)
    {
        currentCount++;
        this.StateHasChanged();
    }
}

【问题讨论】:

    标签: c# asp.net-core blazor


    【解决方案1】:

    运行上面的代码我得到以下异常,在 IncrementCount 函数中抛出:

    System.InvalidOperationException: '当前线程未与 Dispatcher 关联。触发渲染或组件状态时,使用 InvokeAsync() 将执行切换到 Dispatcher。'

    将 StateHasChanged 调用传递给 InvokeAsync 解决了这个问题:

    InvokeAsync(this.StateHasChanged);
    

    【讨论】:

    • 替换你的 this.StateHasChanged();与答案的最后一行一致 - 在 IncrementCount 函数中
    • 你愿意接受这个答案吗,它对你有用吗?
    猜你喜欢
    • 2017-03-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多