简体   繁体   English

StateHasChanged 未更新组件

[英]StateHasChanged not updating component

I have two components, one is used to list all students and the other shows details of a selected student.我有两个组件,一个用于列出所有学生,另一个显示所选学生的详细信息。

Here are the parent components for both:以下是两者的父组件:

<p> Id of student @id </p>

<Students onStudentSelected="@getStudentId"> </Students>

<Student StudentId="@id"> </Student>


@code {
    private int id; 

    private void getStudentId (int e) {
        id = e;
        stateHasChanged();
    }
}

Now here is the thing,the <Students> </Students> component works without issue, ie I can see list of students and when clicked on one, the id of the student is assigned to id and this is displayed inside the <p></p> tags.现在事情是这样的, <Students> </Students>组件可以正常工作,即我可以看到学生列表,当单击一个时,学生的 id 被分配给id并显示在<p></p>标签。

But the <Student> </Student> component is not refreshing.但是<Student> </Student>组件并不令人耳目一新。 If I manually give the Student component an id then I can see the Student details.如果我手动给 Student 组件一个 id,那么我可以看到 Student 的详细信息。

So, for some reason stateHasChanged();所以,出于某种原因stateHasChanged(); has no effect here.在这里没有效果。


If you want to see what these two components look like, it is as simple as:如果你想看看这两个组件长什么样子,很简单:

Students学生

@foreach(var std in StudentsJSON) {
  <p @onclick="() => selectStudent(std.id)"> @std.name </p>
}

@code {
    [Parameter]
    public EventCallback<int> onStudentSelected { get; set; }

    async Task selectStudent(int e){
        await onStudentSelected.InvokeAsync(e)
        // StateHasChanged(); tried here doesn't work
    }
}

Student学生

@using Newtonsoft.Json 
@using System.Net.Http.Headers

@if(JsonResponseContent == null) {
    <p> No student found </p>
}else{
    
    @foreach(var st in JsonResponseContent) {
      <p> @st.age / @st.name / @st.subject </p>
    }
}


@code {
    [Parameter] public int id { get; set; }

    Student JsonResponseContent; 

    protected override async Task OnInitializedAsync(){
   using (HttpClient client = new HttpClient())
    {
        ...
        JsonResponseContent = JsonConvert.DeserializeObject<Student>(ResponseContent);
    }    
    }
}

I don't know why the refresh is not working.我不知道为什么刷新不起作用。

In Student component call api in OnParametersSetAsync() methodOnParametersSetAsync()方法中的Student组件调用 api

protected override async Task OnParametersSetAsync(){
   using (HttpClient client = new HttpClient())
   {
        ...
        JsonResponseContent = JsonConvert.DeserializeObject<Student(ResponseContent);
    }    
    }
}

OnInitializedAsync gets call only once in component lifecycle while OnParametersSetAsync every time parameter value changes (in your example id ). OnInitializedAsync在组件生命周期中仅调用一次,而OnParametersSetAsync每次参数值更改时(在您的示例id中)。 More info . 更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM