简体   繁体   中英

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.

But the <Student> </Student> component is not refreshing. If I manually give the Student component an id then I can see the Student details.

So, for some reason 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() method

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 ). More info .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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