每当父组件更新时,我们如何渲染子组件?

How can we render child component whenever parent component is updated?

子组件根据作为参数传递给子组件的对象的一组属性构造一个字段。在下面的示例中,当父组件中的任何地址字段发生变化时,子组件如何动态呈现?感谢您的任何建议!

父组件如下使用子组件并传递参数parentObj

父组件:

<Child ChildObj="@parentObj" />

子组件:

<div class="col-8 flex-wrap">
    @Address
</div>

@code {

[Parameter]
public Person ChildObj { get; set; }

public string Address { get; set; }


 protected override async Task OnInitializedAsync()
    {
        await Task.Run(() => { 
            if (ChildObj != null)
            {
                Address = ChildObj.Address1 + " " + ChildObj.Address2 + " " + ChildObj.City + " " + ChildObj.State + " " + ChildObj.Zip
            }
        });

    }
}

这里的问题是 OnInitializedAsync 只在组件中第一次设置参数时被调用,你需要使用 OnParametersSet 将在以下情况下调用:

OnParametersSetAsync or OnParametersSet are called:

  • After the component is initialized in OnInitializedAsync or OnInitialized.
  • When the parent component re-renders and supplies: Only known primitive immutable types of which at least one parameter has changed. Any complex-typed parameters. The framework can't know whether the values of a complex-typed parameter have mutated internally, so it treats the parameter set as changed.
<div class="col-8 flex-wrap">
    @Address
</div>

@code {

    [Parameter]
    public Person ChildObj { get; set; }

    public string Address { get; set; }

    // using OnParametersSet
    protected override void OnParametersSet()
    {
        if (ChildObj != null)
        {
            Address = ChildObj.Address1 + " " + ChildObj.Address2 + " " + ChildObj.City + " " + ChildObj.State + " " + ChildObj.Zip
        }
    }
}