Skip to content

自定義組件

nextTick

TIP

該API使用方法為: wx.nextTick(function callback)

  • 功能說明: 延遲一部分操作到下一個時間片再執行(類似於setTimeout)。

  • 參數及說明: function callback, 因為自定義組件中的setData和triggerEvent接口本身是同步的操作,當這幾個接口被連續調用時,都是在一個同步流程中執行完的,囙此若邏輯不當可能會導致出錯。

    一個極端的案例:當父組件的setData引發了子組件的triggerEvent,進而使得父組件又進行了一次setData,期間有通過wx:if語句對子組件進行卸載,就有可能引發錯誤,所以對於不需要在一個同步流程內完成的邏輯,可以使用此接口延遲到下一個時間片再執行。

  • 示例代碼:

js
Component({
  doSth() {
    this.setData({ number: 1 }) // Executed directly within the current synchronous process

    wx.nextTick(() => {
      this.setData({ number: 3 }) // Executed after the current synchronous process ends, in the next time slice.
    })

    this.setData({ number: 2 }) // Executed directly within the current synchronous process
  }
})