美文网首页
Cannot read property 'setDat

Cannot read property 'setDat

作者: 钟德明 | 来源:发表于2018-11-27 02:27 被阅读133次

    背景:用 wx.request 请求到数据后,想 this.setData 来改变某个按钮的内容。发现 this.setData 会报错「Cannot read property 'setData' of null」

    示例一:为错误示例 ,会出现 this.setData is not a function 的报错,原因是此时的this对象指的是setTimeout 里面的匿名函数对象 , 但是在这种情况下还是想动态渲染视图,就需要把当前的this的状态保存起来,然后在 setTimeout 里面的匿名函数对象内调用。如示例二

    片段1
      onLoad:function(){
        setTimeout(function () {
          this.setData({
            open: 111
          },1000)
        })
      },
    

    示例二:保存当前对象的this状态,在 setTimeout 里面的匿名函数对象内调用 , 此时能够做到动态选择视图同时数据和视图都不会出错

    片段2
      onLoad:function(){
        var that= this;
        setTimeout(function () {
          that.setData({
            open: 111
          },1000)
        })
      },
    

    参考
    https://blog.csdn.net/qq_35713752/article/details/78879984

    相关文章

      网友评论

          本文标题:Cannot read property 'setDat

          本文链接:https://www.haomeiwen.com/subject/svrwqqtx.html