在实际开发过程中遇到 warning: Now you can provide attr "wx:key" for a "wx:for" to improve performance.
这是我在做轮播图时发现的,以下是官网的原代码。
<swiper
indicator-dots="{{indicatorDots}}"
autoplay="{{autoplay}}"
interval="{{interval}}"
duration="{{duration}}"
>
<block wx:for="{{imgUrls}}">
<swiper-item>
<image src="{{item}}" class="slide-image" width="355" height="150" />
</swiper-item>
</block>
</swiper>
网上资料:
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-items="{{userInfoList}}" >,会出现warning: Now you can provide attr "wx:key" for a "wx:for" to improve performance. 如果明确知道该列表是静态,或者不必关注其顺序,可以选择忽略。
推荐array 的 每一个item都添加一个唯一识别的property来管理,这样就可以去掉warning,如果使用保留关键字,好像会出现显示的item都是最后一个的
<block wx:for-items="{{userInfoList}}" wx:key="userInfoListId">
后面这话是关键。。。