反应-未处理的拒绝(TypeError)this.function不是函数

时间:2019-08-04 15:15:46

标签: javascript reactjs

我试图在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
        })
      }
    })
  }

}

0 个答案:

没有答案