data: { list: [], keywords: '', popular: [] }, onSearch(e){ this.setData({ keywords: e.detail.value }) }, searchGoods(e) { console.log(this.data.keywords); // wx.navigateTo({ // url: '/pages/jdsearchof/jdsearchof', // }) },这段代码为什么打印出来的是空值
时间: 2024-04-21 07:25:16 浏览: 21
根据这段代码,当`searchGoods`函数被调用时,会打印出`this.data.keywords`的值。但是,如果在调用`searchGoods`函数之前,没有先调用`onSearch`函数,将`keywords`的值设为非空字符串,那么`this.data.keywords`就是空值。因此,请先在页面中输入一些关键词,然后调用`onSearch`函数,使`keywords`的值变为非空字符串,再调用`searchGoods`函数,就可以看到正确的输出了。
相关问题
data: { list: [], keywords: '', popular: [] }, onSearch(e){ // console.log(e.detail.value) this.setData({ keywords: e.detail.value }) }, searchGoods(e) { console.log(this.detail.keywords); // wx.navigateTo({ // url: '/pages/jdsearchof/jdsearchof', // }) },看一下这段代码的错误
这段代码中的错误在 `searchGoods` 函数中。具体来说,`console.log(this.detail.keywords)` 这行代码会导致一个错误,因为 `detail` 是一个未定义的变量,而 `keywords` 是在 `data` 对象中定义的。因此,正确的代码应该是 `console.log(this.data.keywords)`。
修改后的代码如下:
```
data: {
list: [],
keywords: '',
popular: []
},
onSearch(e) {
this.setData({
keywords: e.detail.value
})
},
searchGoods(e) {
console.log(this.data.keywords);
// wx.navigateTo({
// url: '/pages/jdsearchof/jdsearchof',
// })
},
```
这样就可以正确地将用户输入的关键字保存到 `keywords` 变量中,并在 `searchGoods` 函数中打印出来了。
微信小程序 this.setData 提示:Cannot read property 'setData' of undefined
这个错误通常是因为在调用 `setData()` 方法时,`this` 对象未被正确绑定。请确保在调用 `setData()` 方法之前,`this` 对象已经被正确地绑定到当前组件实例。你可以使用箭头函数来确保 `this` 对象的正确绑定,例如:
```
// 正确的写法
getData() {
wx.request({
url: 'http://example.com',
success: (res) => {
this.setData({
data: res.data
})
}
})
}
```
如果你使用普通函数,你需要在函数内部保存 `this` 对象的引用,例如:
```
// 错误的写法
getData() {
wx.request({
url: 'http://example.com',
success: function(res) {
// 此处的 this 是 wx.request 的 this,而不是当前组件实例的 this
this.setData({
data: res.data
})
}
})
}
// 正确的写法
getData() {
var that = this;
wx.request({
url: 'http://example.com',
success: function(res) {
// 此处的 this 是 wx.request 的 this,而不是当前组件实例的 this
that.setData({
data: res.data
})
}
})
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)