You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony UX LiveComponent子组件Table无法更新数据求助

问题:Symfony UX LiveComponent子组件Table无法渲染新数据

问题场景

父组件AdminImportChildren通过事件监听器refreshChildrenTableData更新了childrenTableData数据(日志已确认触发),但子组件Table始终无法显示新数据。

解决步骤

1. 修正子组件的数据源传递错误

父组件调用Table时,错误地将:data绑定到了不存在的data变量,实际应该绑定到父组件的childrenTableData属性:

错误代码:

<twig:Molecules:Table :headers="childrenTableHeaders" :data="data" data-live-id="{{ 'childrentable' ~ childrenTableData|length }}" />

修正后代码:

<twig:Molecules:Table :headers="childrenTableHeaders" :data="childrenTableData" data-live-id="childrentable" />

2. 移除动态生成的data-live-id

动态生成的data-live-id会在数据长度变化时创建新的组件实例,而非更新现有组件。改为固定ID可确保组件实例稳定,让LiveComponent能正确跟踪状态变化。

3. 清理子组件无用代码(可选)

子组件的onDataUpdate方法目前仅读取$this->data,无实际业务逻辑,可直接移除简化代码:

修正后的Table.php:

<?php

namespace App\UI\Http\Twig\Components\Molecules;

use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent]
final class Table
{
    use DefaultActionTrait;

    #[LiveProp] public array $headers = [];
    #[LiveProp(updateFromParent: true)] public array $data = [];
}

4. 确保父组件事件监听器触发组件更新

如果import.children事件是在组件外部触发的,需要在refreshChildrenTableData方法末尾手动通知前端更新组件状态:

public function refreshChildrenTableData(): void
{
    $this->logger->info('Refreshing children table data');
    $allChildren = $this->childService->getAllChildren();
    $this->childrenTableData = array_map(function($child) {
        return [
            'voornaam' => $child->getFirstName(),
            'achternaam' => $child->getLastName(),
            'geboortedatum' => $child->getBirthDate()->format('d-m-Y'),
            'bsn' => $child->getSsn(),
        ];
    }, $allChildren);
    
    // 手动触发组件更新通知
    $this->emit('$componentUpdated');
}

验证

完成上述修改后,触发import.children事件,父组件的childrenTableData更新后,子组件Table会自动同步新数据并重新渲染。

内容的提问来源于stack exchange,提问作者O'Niel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 16:12:06