【问题标题】:Blazor page not rerendering after parameter updated参数更新后 Blazor 页面未重新呈现
【发布时间】:2019-09-12 12:21:45
【问题描述】:

我开始使用新的 ASP.NET 核心 Web 应用和 blazor 客户端模板 (3.0.0-preview4-19216-03)。

为了向现有的Counter.razor 页面添加状态,我添加了以下类:

public class GlobalCounter
{
    private int _count;
    public int Count
    {
        get => _count;
        set
        {
            if (_count == value) return;

            _count = value;
            CounterChanged.Invoke(this, new CounterChangedEventArgs(_count));
        }
    }

    public GlobalCounter(int initialCount = 0)
    {
        _count = initialCount;
    }

    public event EventHandler<CounterChangedEventArgs> CounterChanged;
}

public class CounterChangedEventArgs : EventArgs
{
    public int Count { get; }
    public CounterChangedEventArgs(int count)
    {
        Count = count;
    }
}

Startup.cs 中,ConfigureServices 方法中添加了以下内容:

public void ConfigureServices(IServiceCollection services)
{
    var counter = new GlobalCounter();
    services.AddSingleton(counter);
}

接下来我将要注入的单例添加到Counter.razor 页面中:

@inject GlobalCounter _counter;

还在页面的@functions处添加了如下代码:

protected override async Task OnInitAsync()
{
    currentCount = _counter.Count;
    _counter.CounterChanged += CounterChanged;
    await Task.CompletedTask;
}

void CounterChanged(object sender, CounterChangedEventArgs args)
{
    currentCount = args.Count;
}

void IncrementCount()
{
   _counter.Count++;
}

到目前为止,它按预期工作,离开页面或重新加载将保留旧计数。

接下来,我调整了 index.razor 以注入计数器并显示点击次数。

@page "/"
@inject GlobalCounter _counter;

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

You pressed the counter @totalCount times.

@functions {
    private int totalCount = 0;

    protected override async Task OnInitAsync()
    {
        totalCount = _counter.Count;
        _counter.CounterChanged += CounterChanged;
        await Task.CompletedTask;
    }

    void CounterChanged(object sender, CounterChangedEventArgs args)
    {
        totalCount = args.Count;
    }
}

这也可以按预期工作。按计数器页面上的“点击我”按钮并导航回索引页面,将显示正确的计数。

我的问题来了,一旦我将&lt;Counter /&gt; 页面添加为index.razor 中的组件,按下“点击我”按钮将更新组件内的计数,但不会更新索引页上显示的文本。

是否需要显式调用来重新呈现依赖组件或页面之间的某些特定绑定?

【问题讨论】:

    标签: c# blazor


    【解决方案1】:

    在 index.razor 中试试这个:

    void CounterChanged(object sender, CounterChangedEventArgs args)
    {
        totalCount = args.Count;
    
        StateHasChanged();
    }
    

    你必须告诉 Blazor 组件的状态已经改变,她应该重新渲染。

    顺便提一下,Counter 组件中的值会自动更新,因为在触发“单击我”按钮的单击事件后,Blazor 会调用 StateHasChanged 方法。在引发任何事件类型的事件后,会自动调用 StateHasChanged 方法...

    【讨论】:

      猜你喜欢
      • 2021-12-02
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      • 2018-07-26
      • 2018-07-01
      • 2021-03-27
      • 2019-03-09
      • 2019-10-12
      相关资源
      最近更新 更多