如何以特定间隔更新动态 DOM 值?

aru*_*n r 3 c# asp.net-core blazor

我需要通过使用每秒的计时器来动态更新 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

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

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

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

InvokeAsync(this.StateHasChanged);
Run Code Online (Sandbox Code Playgroud)