gpt4 book ai didi

c# - Blazor - 比较上一个和下一个状态

转载 作者:行者123 更新时间:2023-12-04 12:58:47 26 4
gpt4 key购买 nike

我在 Blazor 中有一个来自 api 的学生表,我还收到推送数据以更新学生信息,这基本上是数据库更改时的分数,推送工作正常,分数为正在更新,但我还想将表中已更新的字段的背景颜色更改为红色,仅将 td 标记更改几秒钟,我的代码如下:

@foreach(var student in SS.GetStudents()){
<tr>
<td> student.name </>
<td> student.section </>
// trying to compare between the previous and next state
var stud = SS.GetStuentsCopy().SingleOrDefault(s =>s.Id == student.Id);
var color = "";
if(stud.score != student.score){
color = red;
}
<td class="@color"> student.score </>
</tr>
}

@code{
[Inject]
public StudentsStates SS { get; set;}
public StudentsResponse Students { get; set; }
protected override async Task OnInitializedAsync()
{
// Subscribe to the StateChanged EventHandler
SS.StateChanged +=
SSAdvancedStateChanged;

Students = await Service.GetStudents();
// update the students and the copy together
SS.UpdateStudents(Students)
SS.UpdateStudentsCopy(Students)


//upon receiving students updated score
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/studhub"))
.Build();

hubConnection.On<StudentsResponse>("ReceiveMessage", s =>
{
// update the students after 3 sec update the copy
SS.UpdateStudents(s);


//Here the state is not being updated
// unless there is a new push
// or the issue might be in rendering
// FYI without the sleep also I can see the changes in the color
System.Threading.Thread.Sleep(3000);
SS.UpdateStudentsCopy(s);

}

}}

学生状态.cs
namespace Ctrl.Web.Data
{
public class StudentsStates
{

public StudentsResponse Students { get; set; }
public StudentsResponse StudentsCopy { get; set; }
public StudentsResponse GetStudents(){return Students;}
public StudentsResponse GetStudentsCopy(){return StudentsCopy;}
public void UpdateStudents(Students students){ Students = students;}
public void UpdateStudentsCopy(Students students){ StudentsCopy = students;}

}}

正如我上面所说的,一切正常,除非在一秒钟内进行多次推送,第一个推送的学生分数的背景颜色更改得太快,有时您甚至不会注意到它,因为推送的数据和状态正在更新,我想要的是在不影响下一个推送的学生分数的情况下减慢背景颜色,或者如果有更好的方法来解决这种情况,我们非常感谢您的回答。

最佳答案

我建议为学生行创建一个组件,如下所示:

@foreach(var student in SS.GetStudents())
{
<StudentRow Student={student} />
}

然后在 StudentRow 组件中,您可以创建一个新的私有(private)学生变量,您可以在延迟 3 秒后更新它并在那里进行比较,而不是将 id 保存在列表或另一个副本中:

StudentRow.razor
  <tr>
<td> Student.name </>
<td> Student.section </>
var color = "";
if(StudentCopy.score != Student.score){
color = red;
}
<td class="@color"> student.score </>
</tr>
@code{
public StudentResponse StudentCopy { get; set; }
[Parameter]
public StudentResponse Student { get; set; }

protected override async Task OnParametersSetAsync()
{
await Task.Delay(3000);
StudentCopy = Student;

}
}

OnParametersSetAsync 方法在组件从渲染树中的父级接收参数时调用,并且传入的值已分配给属性。 Read more here

关于c# - Blazor - 比较上一个和下一个状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62087832/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com