首页 文章

未捕获的TypeError:this.updateShelf不是函数

提问于
浏览
1

所以我有一个小小的开始React项目......

我将一个方法从一个组件移动到顶层的App组件中,现在当我在主应用程序组件中调用另一个方法时,它表示它不存在,这对我来说非常混乱 .

selectStateUpdate(book,shelf) {
  console.log("Sel"+JSON.stringify(book)+shelf)
  this.updateShelf(book, shelf);

}
updateShelf = (book, shelf) => {
  console.log("Updating shelf")
  BooksAPI.update(book, shelf)
  .then(() => BooksAPI.getAll())
  .then((books) => {
    this.setState({books})
  })
}

上面你可以看到我试图通过this.updateShelf调用updateShelf . 有关完整上下文,请参阅App.js

运行项目时,当此函数尝试运行时,我在控制台中出现以下错误 .

Uncaught TypeError: this.updateShelf is not a function
    at Object.selectStateUpdate [as updateSelect] (App.js:21)

完整的上下文项目可以查看here.

任何帮助非常感谢,或者如果您需要任何澄清,请询问 .

2 回答

  • 2

    大部分的时间

    this. is not a function error

    由于在错误的上下文中使用“this”而发生这种情况,因此您可以执行其中一种解决方案 . 在该位置,您可以调用selectStateUpdate来执行此操作

    this.selectStateUpdate(book,shelf).bind(this);
    

    或者使用这种语法

    selectStateUpdate = (book, shelf) => {
      console.log("Sel" + JSON.stringify(book) + shelf);
      this.updateShelf(book, shelf);
    };
    
  • 0

    selectStateUpdate(book,shelf) 更改为 selectStateUpdate = (book,shelf) => {} .

    希望这会有所帮助!

相关问题