javascript - React - 未处理的拒绝(TypeError)this.function不是函数
问题描述
我试图this.getUserFavorites()
在一个类方法中调用一个函数,在一个.then()
之后,fetch
但我总是得到这不是一个函数。
我试过没有this
.
我试过在构造函数中使用绑定,例如:
this.getUserFavorites = this.getUserFavorites.bind(this);
export default class Dashboard extends Component {
constructor(){
super();
this.state = {
loggedIn: true,
name: '',
favorites: [],
modalVisible: false
}
}
addToFavorites(coinID){
const url = `${config.API_URL}/users/favorites`;
const authToken = TokenService.getAuthToken();
fetch(url,{
method: 'PATCH',
headers: {
'content-type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify({ coinID })
})
.then( response => {
if(response.ok){
// THIS ISNT WORKING
this.getUserFavorites();
}
})
}
getUserFavorites = () => {
const userID = TokenService.getAuthUserID();
const url = `${config.API_URL}/users/${userID}/favorites`;
fetch(url)
.then( response => {
return response.ok
? response.json()
: alert(response.statusText)
})
.then( data => {
if(data.favorites !== null){
this.setState({
favorites: data.favorites
})
}
})
}
}
解决方案
推荐阅读
- html - 如何使宽度属性从右到左而不是从左到右开始
- java - 如何存储整个对象但只显示它们的名称?
- ubuntu - 为什么在安装最新版本的 npm 时出现错误?
- sql-server - 从 Visual Studio 的 SQL Server 对象资源管理器连接到 Docker Compose SQL Server 并将数据库保存到本地 PC
- php - 总分从高到低排序
- sapui5 - 如何从目的地获取 Web Socket URL?
- f# - 测试投影在 F# 序列上是否一致
- javascript - 如何连接到在 Azure 应用服务中运行的 socket.io 服务器?
- python - 如何使用 sendKeys 从 Selenium 发送 HTML
- javascript - 如何在当前上下文中查找特定的 JavaScript 变量?