WeChat applet - wx:key

wx:key

 

If the position of items in the list will change dynamically or new items are added to the list, and you want the items in the list to maintain their own characteristics and status (such  <input/> as the input content in , <switch/> the selected state of ), you need to use  wx:key to specify the item in the list unique identifier.

 

wx:key The value of is provided in two forms

  1. String, representing a property of item in the array of the for loop, the value of the property needs to be the only string or number in the list, and cannot be changed dynamically.
  2. The reserved keyword  *this represents the item itself in the for loop. This representation requires the item itself to be a unique string or number. For example, when the data change triggers the rendering layer to re-render, the component with the key will be corrected, and the framework will Make sure they are reordered, not recreated, to make sure the components keep their own state and to improve efficiency when the list is rendered.

If not provided  wx:key, one will be reported  warning. If you know that the list is static, or you don't need to pay attention to its order, you can choose to ignore it.

 

<view>
    <switch wx:for="{{objectArray}}" wx:key="unique" style="display:block;">{{item.id}}
    </switch>
    <button bindtap="switch"> Switch </button>
    <button bindtap="addToFront"> Add to the front </button>

    <switch wx:for="{{numberArray}}" wx:key="*this" style="display: block;"> {{item}} </switch>
    <button bindtap="addNumberToFront"> Add to the front </button>
</view>

 

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
    })
  }
})

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326448164&siteId=291194637