Livewire:添加新记录后无法更新子组件

时间:2020-11-12 08:16:57

标签: laravel laravel-livewire

我有一个问题,我无法解决。我将组件的结构设置为:

发布->评论->评论回复

CommentReply发出Post捕获的事件。发布更新评论集。

评论(模型)具有自身关系作为响应。

现在,如果注释为顶级,则视图将更新。但是,如果响应关系已更新,则视图不会显示更新。如果我发出一个刷新事件,该事件映射到$refresh(组件)中的Comment,则组件引发错误:

Uncaught (in promise) TypeError: Cannot read property 'fingerprint' of null

更新

CommentReply.php

public function post_reply () {
     ...
    $new_comment = $this->comment->response()->create($c);
    $this->is_replying = false;
    $this->emit('content:comments:replied', $new_comment);
}

Comment.php(组件)

    public $listeners = [
        'content:comments:replied' => 'replied'
    ];

   public function replied($comment) {
        /*
           received as array because type hinting
           created error of array to string conversion
       */
        $c = new CommentModel($comment); 
        $this->comment->responses->prepend($c);
    }

comment.blade.php

<div>
@foreach($comment->responses as $response)
<div>
     <div>
         {{ $response->comment }}
     </div>

     <livewire:comment-reply :comment="$comment" :key="'comment-' . $response->id" />
</div>
@endforeach
</div>

comment-reply.blade.php

<div x-data="{ replying: @entangle('is_replying') }">
    <button @click="replying = true;" x-show="!replying">Reply</button>
   <div x-show="replying">
       <textarea wire:model.defer="c.comment"></textarea>
       <button wire:click="post_reply">Post</button>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

这就是我的经历...

  1. 创建了一个组件CommentView并将注释显示逻辑移至该组件 comment-view.blade.php
<div>
     <div>
         {{ $comment->comment }}
     </div>

     <livewire:comment-reply :comment="$comment" />
</div>
  1. Comment组件现在有两个变量,$comment$responses,每次CommentReply发出content:comments:replied时,$responses变量为刷新。

Comment.php

    public $listeners = [
        'content:comments:replied' => 'replied'
    ];

   public function replied() {
        $this->responses = $this->comment->responses()->orderBy('created_at', 'desc')->get();
    }

comment.blade.php

<div>
    <livewire:comment-view :comment="$comment" />
    @foreach($responses as $r_comment) 
          <livewire:comment-view :comment="$r_comment" :key="'response-' . $r_comment->id" />
     @endforeach
</div>