当前位置:网站首页>微信小程序Cannot read property 'setData' of null错误
微信小程序Cannot read property 'setData' of null错误
2022-07-22 10:51:00 【萌萌怪】
今天练习使用微信小程序chooseImage的API时遇到了这个小错误,一方面是粗心,一方面也是知识不牢固才犯错。
说到底,是不清楚数据的作用域,去访问了访问不到的数据。
背景:我想通过chooseImage这个API从本地读取一张图片(新数据),然后替换掉之前显示的图片(老数据),从而将读取的图片显示出来。其实也就是更改数据,如图:
通过日志信息可以知道,读取图片是没问题的。
但是将这个地址赋值给image标签的src时,却一直报错。
错误的代码段:
//index.js
Page({
data: {
userimage: "/images/cat.png", //默认的数据!!!!!!!!!!!!!
},
bindViewTap: function() {
//利用API从本地读取一张图片
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
var tempFilePaths = res.tempFilePaths
//将读取的图片替换之前的图片
this.setData({userimage: tempFilePaths[0]}) //修改数据!!!!!!!!!!!!!
}
})
}
})
正确的代码:
//index.js
Page({
data: {
userimage: "/images/cat.png",
},
bindViewTap: function() {
var that=this //!!!!!!!!!“搭桥”
//利用API从本地读取一张图片
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
var tempFilePaths = res.tempFilePaths
//将读取的图片替换之前的图片
that.setData({userimage: tempFilePaths[0]})//!!!!!通过that访问
}
})
}
})
总结:
我想在wx.chooseImage()里面更改离它辣么遥远的userimage的值,使用this,访问不到userImage,所以要在bindViewTap(中间层),加上var that=this,作为桥梁,在wx.chooseImage里面才能通过桥梁that访问到userimage!
边栏推荐
猜你喜欢
pycharm设置
pytest测试框架快速搭建
Redis 系列11--Redis 持久化
【FPGA】:ip核--ibert
基于非线性最坏情况分析的电荷缩放 DAC 中电容器的新棋盘放置和尺寸调整方法
【FPGA】:ip核---乘法器(multiplier)
具有任意电容比的共质心电容阵列的自动生成
Likeshop100%开源无加密-B2B2C多商户商城系统!!
Common centroid capacitor layout generation considering device matching and parasitic minimization
Redis 系列14--Redis Cluster
随机推荐
【FPGA】状态机
Data transfer from one Mysql to another MySQL
Pastel: parasitic matching drive layout and wiring of capacitor array with generalized ratio in charge redistribution sar-adc
模拟电路中晶体管阵列的性能感知公共质心布局和布线 ALIGN
数据倾斜
有源和无源设备的共质心布局:回顾和未来之路
LeetCode - 整数反转
Binary search (recursive function)
Automatic current mirror layout (acml) tool
Lingo 基本使用
A new checkerboard placement and sizing method for capacitors in charge scaling DAC based on nonlinear worst-case analysis
基于非线性最坏情况分析的电荷缩放 DAC 中电容器的新棋盘放置和尺寸调整方法
1072 gas station (30 points)
1091 acute stroke (30 points)
顺序表的创建插入和修改
Rapid construction of selenium testing framework (UI automated testing)
Airtest conducts webui automated testing (selenium)
【FPGA】:频率测量
Automatic generation of common centroid capacitance array with arbitrary capacitance ratio
postman接口测试