blazor 组件未更新 |核心3.0

blazor component not updating | core3.0

正在尝试使用最新模板生成的解决方案。

.

protected override async Task OnInitializedAsync()
    {
        await Task.Run(() =>
        {
            this.svc.Add("string one");
            this.svc.Add("string two");
        });
         await Task.Run(() => StateHasChanged());
    }

<button @onclick="SetCurrentTime"> Time </button>
    <h4>@time</h4>
        
    void SetCurrentTime()
            {
                time = DateTime.Now.ToLongTimeString();
            }

github 这个问题的回购:(点击 AddString 并且计数器应该增加)https://github.com/pkaushik23/mycodeshares/tree/master/CheckRefreshBlazor

您的 NameService 应该通知更改。在 Invoke component methods externally to update state

上了解它

对于您的服务代码,类似于:

public class StringService
{
    public event Func<string, Task> Notify;
    public List<string> Names { get; set; } = new List<string>();
    public void Add(string s)
    {
        this.Names.Add(s);
        if (Notify != null)
        {
            await Notify.Invoke(s);
        }            
    }
}

关于您的组件:

protected override void OnInitialized()
{
    this.svc.Notify += OnNotify;
}

public async Task OnNotify(string s)
{
    await InvokeAsync(() =>
    {            
        StateHasChanged();
    });
}