Am调用api在异步任务OnAfterRenderAsync(bool-firstRender(下加载数据但是jscript是在用户在UI 中加载之前加载的
一旦数据加载到用户列表中,我如何调用js?
背后的代码
protected override async Task OnAfterRenderAsync(bool firstRender)
{
List<User> users = await Getuser(Request);
await jsRuntime.InvokeAsync<IJSObjectReference>("import", "/js/scripts/test.js");
}
UI
<div class="user-list">
<ul>
@foreach (var user in users)
{
<li>
<h5 class="mb-25">@user.name</h5>
</li>
}
</ul>
<div>
使用OnInitializedAsync
检索数据,使用OnAfterRenderAsync
检索js-interop。
在test.js中,您必须导出添加点击事件的函数:
export function addClickEvents() {
// add your js code here
if ($('.user-list').find('li').length) { $('.user-list').find('li').on('click', function (e) { $('.details').toggleClass('show'); }); }
}
然后在导入js模块后,您必须调用以下函数:
private List<User> users;
protected override async Task OnInitializedAsync()
{
users = await Getuser(Request);
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
var module = await jsRuntime.InvokeAsync<IJSObjectReference>("import", "/js/scripts/test.js");
// invoke addClickEvents function
await module.InvokeVoidAsync("addClickEvents");
}
}
同样在UI中,您应该检查列表是否为空。
@if (users != null)
{
<div class="user-list">
<ul>
@foreach (var user in users)
{
<li>
<h5 class="mb-25">@user.name</h5>
</li>
}
</ul>
<div>
}
else
{
<p>Loading...</p>
}
Blazor组件生命周期
在OnAfterRenderAsync((方法中,将用户数据(从API(加载到本地变量。foreach循环处理组件中声明的另一个列表。
用途:
users = await Getuser(Request);
而不是:
List<User> users = await Getuser(Request);
我认为您希望在导入js文件之前将用户呈现到UI,如果这是您想要的,则需要在使用StateHasChanged()
:获得用户列表后,强制组件将更改应用于用户列表
代码背后:
private List<User> users;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
users = await Getuser(Request);
StateHasChanged(); // you need to use StateHasChanged to apply changes
//await Task.Delay(0); // this will give the main thread a chance to apply changes but as the below call is also async operation, you might not need to delay to apply changes
//So first try without delay, if it is not worked try with delay
await jsRuntime.InvokeAsync<IJSObjectReference>("import", "/js/scripts/test.js");
}
UI:
<div class="user-list">
<ul>
@foreach (var user in users ?? Enumerable.Empty<User>()) @*supply empty Enumerable if list is null*@
{
<li>
<h5 class="mb-25">@user.name</h5>
</li>
}
</ul>
<div>