【发布时间】:2020-12-04 18:45:22
【问题描述】:
在我的组件中,我有一个子组件 (FooComponent),我将参数传递给它并获得一个 ref。
Parent.razor
<FooComponent @ref="FooComponentRef" FooParameter="@MyValue"/>
<button @onclick="Test">@MyValue</button>
@code {
FooComponent FooComponentRef { get; set; }
string MyValue { get; set; }
int count { get; set; }
void Test(){
MyValue = "SomeValue" + count++;
FooComponentRef.FooFunction();
}
}
我修改了代码,使其成为一个简单且可测试的示例
我有一个函数 (Test) 将更新在参数中传递的属性 (MyValue 传递给 FooParameter) 并从 ref 调用一个函数 (FooFunction 的 FooComponent) .
在FooComponent里面
FooComponent.razor
<div>
<div>FooParameter: @FooParameter</div>
<div>ValueUsedInFooFunction: @ValueUsedInFooFunction</div>
</div>
@code {
[Parameter]
public string FooParameter { get; set; }
public string ValueUsedInFooFunction { get; set; }
public void FooFunction()
{
// This function is using FooParameter to make some logic
ValueUsedInFooFunction = FooParameter;
}
}
我修改了代码,使其成为一个简单且可测试的示例
它使用FooFunction中的FooParameter来做一些逻辑。
问题是当我更改MyValue并调用FooFunction时,组件还没有更新,所以它使用FooParameter的“旧”值,但我需要使用新设置的值,这是正确的MyValue。
让这个问题难以解决的另一件事是我无法更改 FooFunction(这不是我创建的函数)。
我已经尝试过使用所有方法(StateHasChanged、InvokeAsync),但仍然没有解决方案。
我需要的是我的Test 函数来做类似的事情
void Test(){
MyValue = "SomeValue" + count++;
// Somehow update UI so FooParameter have the correct value of MyValue
FooComponentRef.FooFunction();
}
在小提琴中,当点击按钮并调用Test函数时,你会看到ValueUsedInFooFunction始终是FooParameter的“旧”值,这意味着FooFunction在FooParameter 正在更新中。
【问题讨论】: