在 Blazor 中的两个子组件之间共享数据的最佳方式

Kri*_*nac 7 c# .net-core blazor blazor-client-side asp.net-blazor

我有这个代码。

<ParentComponent>
    <ChildComponet>
         @renderFragment
    </ChildComponent>
    <ChildComponetn>
       <GridComponent Data="@dataList"/>
    </ChildComponent>
</ParentComponent>
Run Code Online (Sandbox Code Playgroud)

其中@renderFragment 是动态渲染组件,网格组件是一些数据的列表,其中包含“添加新”、“编辑记录”、“删除”等操作。

如果我们点击“添加新”,在@renderFragment 中动态打开添加新记录的表单,我们想在提交表单后刷新网格数据,但我们不知道如何在两个子组件之间共享一些数据。编辑表单也是一样,当一些记录被编辑时,我们需要刷新网格组件以显示编辑的数据。如果需要更多关于它的代码和数据,请发表评论。

Isa*_*aac 7

您可以定义一个实现状态模式和通知程序模式的类服务来处理您的对象的状态,将状态传递给对象,并将更改通知订阅者对象。

这是此类服务的一个简化示例,它使父组件能够与其子组件通信。

通知服务.cs

public class NotifierService
{
    private readonly List<string> values = new List<string>();
    public IReadOnlyList<string> ValuesList => values;

    public NotifierService()
    {

    }

    public async Task AddTolist(string value)
    {
        values.Add(value);
        if (Notify != null)
        {
            await Notify?.Invoke();
        }

    }

    public event Func<Task> Notify;
 }
Run Code Online (Sandbox Code Playgroud)

Child1.razor

 @inject NotifierService Notifier
 @implements IDisposable

 <h1>User puts in something</h1>
 <input type="text" @bind="@value" />
 <button @onclick="@AddValue">Add value</button>

 @foreach (var value in Notifier.ValuesList)
 {
    <p>@value</p>
 }


@code {
    private string value { get; set; }

    public async Task AddValue()
    {
        await Notifier.AddTolist(value);
    }

    public async Task OnNotify()
   {
      await InvokeAsync(() =>
      {
        StateHasChanged();
      });
   }


  protected override void OnInitialized()
  {
     Notifier.Notify += OnNotify;
  }


   public void Dispose()
   {
       Notifier.Notify -= OnNotify;
   }
}
Run Code Online (Sandbox Code Playgroud)

Child2.razor

@inject NotifierService Notifier

<h1>Displays Value from service and lets user put in new value</h1>

<input type="text" @bind="@value" />

<button @onclick="@AddValue">Set Value</button>

@code {
   private string value { get; set; }
   public async Task AddValue()
   {
      await Notifier.AddTolist(value);

   }

 }
Run Code Online (Sandbox Code Playgroud)

用法

 @page "/"

 <Child1></Child1>
 <Child2></Child2>
Run Code Online (Sandbox Code Playgroud)

启动.配置服务

services.AddScoped<NotifierService>();
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助...