微信小程序关于this

本文记录了在学习微信小程序时遇到的一个关于`this`的陷阱。在`showModal()`的`success`回调中,由于`this`指向的改变导致`this.setData()`方法出错。解决方案是保存`this`的引用并在回调中使用,以确保正确调用`setData()`。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近学习微信小程序,发现一个关于this的坑,记录一下:

代码:

// pages/post/post-detail/post_detail.js
var postsData = require("../../../data/posts-data.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    postData: {},
    collected: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var id = options.id;
    this.data.currentpostId = id;
    var postData = postsData.postList[id];
    // this.data.postData = postData;
    this.setData({
      postData: postData
    })

    var postsCollected = wx.getStorageSync("posts_Collected");
    if (postsCollected) {
      var postCollected = postsCollected[id];
      this.setData({
        collected: postCollected
      })
    } else {
      var postsCollected = {};
      postsCollected[id] = false;
      wx.setStorageSync("posts_Collected", postsCollected);
    }
  },
  onCollectionTap: function(event) {
    var postsCollected = wx.getStorageSync("posts_Collected");
    var postCollected = postsCollected[this.data.currentpostId];
    //取反
    postCollected = !postCollected;
    postsCollected[this.data.currentpostId] = postCollected;
    this.showModal(postsCollected, postCollected);
  },

  showModal: function (postsCollected, postCollected) {
    wx.showModal({
      title: '收藏',
      content: postCollected?'收藏该文章?':'取消收藏该文章?',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#333',
      confirmText: '确认',
      confirmColor: '#405f80',
      success: function (res) { 
        if(res.confirm){
          wx.setStorageSync("posts_Collected", postsCollected);
          //更新数据绑定变量,切换图片
          //此处代码错误
          this.setData({
            collected: postCollected
          })
        }
      },
      fail: function (res) {

       },
      complete: function (res) {

       },
    })
  },
  showToast: function (postsCollected, postCollected) {
    //更新文章是否缓存
    wx.setStorageSync("posts_Collected", postsCollected);
    //更新数据绑定变量,切换图片
    this.setData({
      collected: postCollected
    })
    wx.showToast({
      title: postCollected?'收藏成功':'取消收藏成功',
      icon:'success',
      duration:1000
    })
  }
})

报错:showModal()方法中success回调函数中this.setData()方法错误

原因:在javascript中,this代表着当前对象,会随着程序的执行过程中的上下文改变 。这里最外面的setData()没有报错,因为onLoad()方法是在当前page下的方法,this就是当前对象;而在showModal的方法中,又回调了success(),那么当前对象已经改变,所以当前对象不再是this。

解决方法:

将当前对象复制一份放在函数外面,然后在success方法中使用that.setData():

//将当前对象复制一份
var that = this; 
showModal: function (postsCollected, postCollected) {
    wx.showModal({
      title: '收藏',
      content: postCollected?'收藏该文章?':'取消收藏该文章?',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#333',
      confirmText: '确认',
      confirmColor: '#405f80',
      success: function (res) { 
        if(res.confirm){
          wx.setStorageSync("posts_Collected", postsCollected);
          //更新数据绑定变量,切换图片
          //此处使用that
          that.setData({
            collected: postCollected
          })
        }
      },
      fail: function (res) {

       },
      complete: function (res) {

       },
    })
  },

再次运行,解决。

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值