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

Do I need to install babel to be able to write ES6 code in my react-app?

我创建了一个 React 应用程序并开始尝试将它连接到我使用 MongoDB 准备的服务器。每当我检查我的本地主机以查看反应应用程序时,错误 "expression expected" 不断出现,尽管我的代码似乎是正确的。

我使用下面的代码创建了一个名为 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 显示了控制台中显示的问题。

我该如何解决这个错误?

在你的箭头函数中,你在 => 之间有一个 space。所以请指正。

此外,如果您使用的是 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;

这里有两个错误:

1- 在你的 HttpService 文件中你的箭头函数有一个语法错误,space 在 => 之间,它应该是这样的:

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

export default HttpService;

2- 在 App.js 中,您在普通函数中定义了一个 构造函数 ,这在 javascript 中无效,您必须切换 App.js 从函数到 class 或者你可以在你的正常函数中使用钩子 (useEffect),像这样:

 React.useEffect(() => {
    http.getProducts();
  }, [])

你终于有了 create-react-app,babel is already included 所以你可以在你的代码中使用 ES6。