为什么出错“;” 当不需要分号时,预期会在我的app.js文件中发生吗?

Joh*_*con 1 javascript reactjs airtable

我正在用React创建一个Chrome扩展程序,该扩展程序使用Airtable数据库,从教程中逐字复制代码。在我的app.js中,我遵循在构造函数方法下添加名为“ componentDidMount”的方法的说明,该方法调用Airtable API从中获取数据值。

我在第一行的左花括号中收到一个错误:

componentDidMount() {
  fetch('https://api.airtable.com/v0/app172rHs45CgT8UH/Favorites? api_key=YOUR_API_KEY')
  .then((resp) => resp.json())
  .then(data => {
     this.setState({ movies: data.records });
  }).catch(err => {

  });
}
Run Code Online (Sandbox Code Playgroud)

确切的错误是';' 预期。ts(1005)

我从教程中复制了代码行,并设置了Airtable。我还粘贴了自己的唯一ID密钥,因此对于为什么会发生此错误感到困惑。我认为问题实际上不是分号,因为我尝试添加一个,但仍然会抛出该错误。我提供了紧接在问题行前后的代码的屏幕快照,以及教程的相关部分。

这就是本教程要添加到我的app.js中的内容

错误突出显示,并带有上下文代码

这是教程链接,尽管我当然不希望有人真正阅读它。如果对了解上下文有帮助,则本教程的这一部分已经过了一半,标题为:“集成React和Airtable”

https://upmostly.com/tutorials/create-simple-web-app-react-airtable/#introduction

如果有人能告诉我发生了什么,我将不胜感激。我对这个特定代码的理解还不是很强,因为我只是想完成本教程并理解其中的每个部分。

如果您需要其他信息/代码来知道出了什么问题,请告诉我。非常感谢!

Lef*_*ium 7

Method componentDidMount() should go inside the class App (where the constructor is):

class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
          movies: [],
        };
    }

    componentDidMount() {
        fetch('https://api.airtable.com/v0/appgOPm5an5ZzNvkk/favorites?api_key=YOUR_API_KEY')
        .then((resp) => resp.json())
        .then(data => {
           this.setState({ movies: data.records });
        }).catch(err => {
            // Error 
        });
    }    
}
Run Code Online (Sandbox Code Playgroud)

This makes componentDidMount() a member method of class App. Classes are a way to logically group related methods and variables together into a single object.

Just adding function fixes the syntax error, but does not remove the underlying problem: your program will not behave in the way expected! In this case, React will be looking for a method componentDidMount() in your App class. Since React can't find it, your code will not be executed; the default behavior will run instead.

Some tips for how to recognize componentDidMount() should be wrapped inside a class:

  • componentDidMount() looks like a function, but there is no function keyword. Methods in classes are allowed to omit the function keyword.
  • componentDidMount() is indented. This is a convention for indicating the code is inside a code block.
  • The ... ellipses before and after componentDidMount() indicate code has been "hidden." If you're following that tutorial, this should make you wonder what code should come after componentDidMount(). The ... ellipses in the previous code snippet hint that something should be inserted there.
  • A basic understanding of JavaScript classes will also help a lot. Here are two good resources. A short reference and a detailed excerpt from a great book on JavaScript:

BTW componentDidMount()是React API的一部分。