首页 > 解决方案 > 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
        })
      }
    })
  }

}

标签: javascriptreactjs

解决方案


推荐阅读