我试图在this.getUserFavorites()
之后的.then()
内部的类方法中调用函数fetch
,但是我总是认为这不是函数。
我尝试过没有this
的情况。
我尝试在构造函数中使用bind,例如:
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
})
}
})
}
}