[微信小程序]控制台弹出 warning: Now you can provide attr "wx:key" for a "wx:for" to improve performance

在小程序控制台开发中遇到提示: warning: Now you can provide attr "wx:key" for a "wx:for" to improve performance.

查找资料与查看官方文档发现原因大致如下:

官方解释:
wx:key
如果列表中项目的位置会动态改变或者有新的项目添加到列表中,并且希望列表中的项目保持自己的特征和状态(如 <input/> 中的输入内容,<switch/> 的选中状态),需要使用 wx:key 来指定列表中项目的唯一的标识符。

网上资料:
wx:key 的值以两种形式提供

1、wx:key="property" 其中property是代表在 for 循环的 array 中 item 的某个 property,该 property 的值需要是列表中唯一的字符串或数字,且不能动态改变。类似于字典的key值

2、wx:key="*this", 保留关键字 *this 代表在 for 循环中的 item 本身,这种表示需要 item 本身是一个唯一的字符串或者数字,如:

当数据改变触发渲染层重新渲染的时候,会校正带有 key 的组件,框架会确保他们被重新排序,而不是重新创建,以确保使组

件保持自身的状态,并且提高列表渲染时的效率。


不添加wx:key情况:

        <block wx:for="{{navItems}}" wx:for-item="item" wx:for-index="itemIdx">
            <view bindtap="navItemTap" class="top-btn {{navBtnSelectIdx == itemIdx ? 'top-hoverd-btn' : ''}}" data-index="{{itemIdx}}" data-cid="{{item.cid}}">{{item.title}}</view>
        </block>

会出现warning: Now you can provide attr "wx:key" for a "wx:for" to improve performance. 如果明确知道该列表是静态,或者不必关注其顺序,可以选择忽略。

推荐array 的 每一个item都添加一个唯一识别的property来管理,这样就可以去掉warning,如果使用保留关键字,好像会出现显示的item都是最后一个的

        <block wx:for="{{navItems}}" wx:key="navItems" wx:for-item="item" wx:for-index="itemIdx">
            <view bindtap="navItemTap" class="top-btn {{navBtnSelectIdx == itemIdx ? 'top-hoverd-btn' : ''}}" data-index="{{itemIdx}}" data-cid="{{item.cid}}">{{item.title}}</view>
        </block>

好了, 再也没有烦人的提示了!
--------------------- 

原文:https://blog.csdn.net/aerchi/article/details/73547970 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/qq_21041889/article/details/89643629