无法从父组件调用中填充 Blazor 组件。

huangapple go评论82阅读模式
英文:

Can't populate Blazor component from parent call

问题

我要创建一个 "Repository" Blazor 组件,并在调用方法时填充该组件。你能解释为什么这段代码不起作用吗?

当从父组件/页面调用 Load() 方法时:

<Repository @ref="repo" />
...
repo.Load();
<h3>Repository</h3>

@if (Elements == null)
{

}
else
{
    <span>@Elements.Count 个元素</span>
    <ul class="list-group">
        @foreach (var element in Elements)
        {
            <li class="list-group-item">@element</li>
        }
    </ul>
}

@code {
    protected List<string>? Elements { get; set; }

    public async Task Load()
    {
        Elements = await Task<List<string>>.Run(() =>
        {
            List<string> liste = new();
            liste.Add("a1");
            liste.Add("b1");
            liste.Add("c1");
            return liste;
        });
    }
}

注意:我已经将你的代码翻译成中文,代码部分不做翻译。

英文:

I want to create a "Repository" blazor component and populate this component when a clla a method.
Can you explain why this code is not working ?
when the method Load() is called from a parent component/page

&lt;Repository @ref=&quot;repo&quot;/&gt;
...
repo.Load();
&lt;h3&gt;Repository&lt;/h3&gt;

@if(Elements==null)
{
	
} else
{
	&lt;span&gt;@Elements.Count elements&lt;/span&gt;
	&lt;ul class=&quot;list-group&quot;&gt;
		@foreach (var element in Elements)
		{
			&lt;li class=&quot;list-group-item&quot;&gt;@element&lt;/li&gt;
		}
	&lt;/ul&gt;
}


@code {
	protected List&lt;string&gt;? Elements { get; set; }

	public async Task Load()
	{
		Elements = await  Task&lt;List&lt;string&gt;&gt;.Run(() =&gt;
		{
			List&lt;string&gt; liste = new();
			liste.Add(&quot;a1&quot;);
			liste.Add(&quot;b1&quot;);
			liste.Add(&quot;c1&quot;);		
			return liste;

		});			
	}
}

答案1

得分: 3

你可以在 Load() 方法的最后一行添加 await InvokeAsync(StateHasChanged);,这样可以将渲染请求放入队列中,因为你的 Load() 方法已经是一个 async Task

英文:

Your call to repo.Load() is not triggering a render, likely because it's outside the component lifecycle. You can place a render request on the queue using StateHasChanged. Since your Load() method is already an async Task, I would recommend adding await InvokeAsync(StateHasChanged); as the very last line in that method.

huangapple
  • 本文由 发表于 2023年7月18日 16:53:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76711052.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定