這幾天在研究微信小程序,看到官方文檔里的列表渲染中wx:key字段碎捺,官方文檔如下
如果列表中項(xiàng)目的位置會動態(tài)改變或者有新的項(xiàng)目添加到列表中,并且希望列表中的項(xiàng)目保持自己的特征和狀態(tài)(如中的輸入內(nèi)容,<switch/>的選中狀態(tài)),需要使用wx:key來指定列表中項(xiàng)目的唯一的標(biāo)識符郊霎。
wx:key的值以兩種形式提供
字符串,代表在 for 循環(huán)的 array 中 item 的某個 property爷绘,該 property 的值需要是列表中唯一的字符串或數(shù)字,且不能動態(tài)改變进倍。
保留關(guān)鍵字*this代表在 for 循環(huán)中的 item 本身土至,這種表示需要 item 本身是一個唯一的字符串或者數(shù)字,如:
當(dāng)數(shù)據(jù)改變觸發(fā)渲染層重新渲染的時候猾昆,會校正帶有 key 的組件陶因,框架會確保他們被重新排序,而不是重新創(chuàng)建垂蜗,以確保使組件保持自身的狀態(tài)楷扬,并且提高列表渲染時的效率。
如不提供wx:key贴见,會報一個warning烘苹, 如果明確知道該列表是靜態(tài),或者不必關(guān)注其順序片部,可以選擇忽略镣衡。
Page({
?data: {
??objectArray: [
???{id: 5, unique:?'unique_5'},
???{id: 4, unique:?'unique_4'},
???{id: 3, unique:?'unique_3'},
???{id: 2, unique:?'unique_2'},
???{id: 1, unique:?'unique_1'},
???{id: 0, unique:?'unique_0'},
??],
??numberArray: [1, 2, 3, 4]
?},
?switch:?function(e) {
??const length =?this.data.objectArray.length
??for?(let i = 0; i < length; ++i) {
???const x = Math.floor(Math.random() * length)
???const y = Math.floor(Math.random() * length)
???const temp =?this.data.objectArray[x]
???this.data.objectArray[x] =?this.data.objectArray[y]
???this.data.objectArray[y] = temp
??}
??this.setData({
???objectArray:?this.data.objectArray
??})
?},
?addToFront:?function(e) {
??const length =?this.data.objectArray.length
??this.data.objectArray = [{id: length, unique:?'unique_'?+ length}].concat(this.data.objectArray)
??this.setData({
???objectArray:?this.data.objectArray
??})
?},
?addNumberToFront:?function(e){
??this.data.numberArray = [?this.data.numberArray.length + 1 ].concat(this.data.numberArray)
??this.setData({
???numberArray:?this.data.numberArray
??})
?}
})
在這里我自己琢磨了一會,并測試了下,個人理解的意思是廊鸥,當(dāng)指定了wx:key之后望浩,switch控件相當(dāng)于有了各自的標(biāo)志,在執(zhí)行換位置的方法時當(dāng)前操作的按鈕也會跟著換位置惰说,且切換后狀態(tài)不變磨德,如果沒有wx:for則當(dāng)前的按鈕在切換后位置不會發(fā)生改變,位置會固定在哪里