首页 > 解决方案 > Laravel Livewire key() 期望参数 1 是数组,给定整数 | 嵌套组件 | 在循环中加载组件

问题描述

我已经使用Laravel livewire有一段时间了,我有一个嵌套组件,它是我网站的产品列表,在该列表中,我还有另一个用于将产品添加到愿望清单的组件。根据此处所述的文档,它说

“类似于 VueJs,如果你在循环中渲染一个组件,Livewire 无法跟踪哪个是哪个。为了解决这个问题,livewire 提供了一种特殊的“关键”语法:”

像这样:

<div>
    @foreach ($users as $user)
        @livewire('user-profile', $user, key($user->id))
    @endforeach
</div>

这是我的项目中的代码片段。

<div>
    @foreach($products as $product)
        <div class="product-box white-bg mb-8" data-dusk="product"> 
             {{-- here im passing product id as param in key(),  'productList' is a static value for a variable of mount(). --}}
                @livewire('desktop.wish-list-add', $product, key($product->id), 'productList')

            <div class="product-content d-flex justify-content-between align-items-center p-5">
                ............... 

    @endforeach
    {{ $products->links() }}
</div>

问题是当我尝试将 $product->id 作为 key() 的参数传递时,它给出了错误

key() expects parameter 1 to be array, integer given

但是文档清楚地表明我们必须将 id 作为参数传递。到目前为止,有人遇到过这个问题吗?

标签: laravellaravel-livewire

解决方案


@livewire('photos.photo-wire', ['photo' => $photo], key($photo->id))

代替

@livewire('photos.photo-wire', ['photo' => $photo, key($photo->id)])

因为这会产生错误:

key() expects parameter 1 to be array, integer given


推荐阅读