我有一个来自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);
}
}}
StudentsStates.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;}
}}
正如我上面所说的,一切都运行良好,除非在几秒钟内进行多次推送,但第一次推送的学生分数的背景颜色变化太快,有时由于推送的数据和状态,您甚至都不会注意到它正在更新中,我想要的是放慢背景色,而不会影响下一个推送的学生成绩,或者如果有解决此问题的更好方法,您的答案将受到高度赞赏。
答案 0 :(得分:1)
我建议为学生行创建一个组件,如下所示:
@foreach(var student in SS.GetStudents())
{
<StudentRow Student={student} />
}
然后,您可以在StudentRow组件内部创建一个新的私有学生变量,在其中您会在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方法,当组件已从渲染树中的其父级接收到参数并且传入值已分配给属性时调用。 here