關於微信小程序開發wx:key字段標籤的理解

這幾天在研究微信小程序,看到官方文檔裏的列表渲染中wx:key字段,官方文檔以下小程序

若是列表中項目的位置會動態改變或者有新的項目添加到列表中,而且但願列表中的項目保持本身的特徵和狀態(如 <input/> 中的輸入內容,<switch/> 的選中狀態),須要使用 wx:key 來指定列表中項目的惟一的標識符。微信小程序

wx:key 的值以兩種形式提供微信

  1. 字符串,表明在 for 循環的 array 中 item 的某個 property,該 property 的值須要是列表中惟一的字符串或數字,且不能動態改變。
  2. 保留關鍵字 *this 表明在 for 循環中的 item 自己,這種表示須要 item 自己是一個惟一的字符串或者數字,如:

當數據改變觸發渲染層從新渲染的時候,會校訂帶有 key 的組件,框架會確保他們被從新排序,而不是從新建立,以確保使組件保持自身的狀態,而且提升列表渲染時的效率。框架

如不提供 wx:key,會報一個 warning, 若是明確知道該列表是靜態,或者沒必要關注其順序,能夠選擇忽略。dom

 

Page({測試

 data: {this

  objectArray: [code

   {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

  })

 }

})

在這裏我本身琢磨了一會,並測試了下,我的理解的意思是,當指定了wx:key以後,switch控件至關於有了各自的標誌,在執行換位置的方法時當前操做的按鈕也會跟着換位置,且切換後狀態不變,若是沒有wx:for則當前的按鈕在切換後位置不會發生改變,位置會固定在哪裏

相關文章
相關標籤/搜索