我需要安装babel才能在我的react-app中编写ES6代码吗?

问题描述 投票:0回答:2

我创建了一个React应用,并开始尝试将其连接到使用MongoDB准备好的服务器。每当我检查本地主机以查看react应用程序时,尽管我的代码似乎是正确的,但仍然不断出现“预期的表达式”错误。

我使用下面的代码创建了一个名为http-service.js的文件。

import 'whatwg-fetch';

class HttpService {
    getProducts = () = > {
        fetch('http://localhost:3000/product')
        .then(response => {
            console.log(response.json());
    })
    }
}

export default HttpService;

然后我将其导入到我的App.js文件中,如下所示。

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import HttpService from "../services/http-service";

const http = new HttpService();

function App() {
  constructor(props){
      super(props);
      http.getProducts();
  };

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Welcome to The Swag Shop
        </a>
      </header>
    </div>
  );
}

export default App;

image显示了控制台中显示的问题。

我该如何解决此错误?

javascript reactjs syntax create-react-app
2个回答
0
投票

在箭头功能中,=>之间有一个空格。所以请纠正它。

此外,如果您使用的是create-react-app,则开箱即用的Babel已经安装好了。

喜欢此

import 'whatwg-fetch';

class HttpService {
    getProducts = () => { // remove space between = and >
        fetch('http://localhost:3000/product')
        .then(response => {
            console.log(response.json());
    })
    }
}

export default HttpService;

0
投票

HttpService文件中,箭头函数存在语法错误,在=>之间有一个空格,应该是这样的:

class HttpService {
    getProducts = () => {
        fetch('http://localhost:3000/product')
        .then(response => {
            console.log(response.json());
    })
    }
}

export default HttpService;

也在App.js中,您在常规函数中定义了constructor,这在javascript中无效,您必须将App.js切换为类,或者可以使用钩子(useEffect)

最后,对于create-react-app u are,babel已经包含在内,因此您可以在代码中使用ES6。

© www.soinside.com 2019 - 2024. All rights reserved.