我创建了一个react应用程序,并开始尝试将其连接到我使用MongoDB准备的服务器。每当我检查本地主机以查看react应用程序时,尽管我的代码似乎是正确的,但错误"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;
此图显示控制台中显示的问题。
我应该如何解决此错误?
在箭头函数中,=
和>
之间有一个空格。所以请更正。
此外,如果您正在使用create-react应用程序,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
文件中,你的箭头函数有语法错误,=
和>
之间有一个空格,应该是这样的:
class HttpService {
getProducts = () => {
fetch('http://localhost:3000/product')
.then(response => {
console.log(response.json());
})
}
}
export default HttpService;
2-在App.js
中,你在一个普通函数中定义了一个构造函数,这在javascript中是无效的,你必须将App.js
从函数切换到类,或者你可以在你的普通函数中使用钩子(useEffect(
React.useEffect(() => {
http.getProducts();
}, [])
最后,通过create-react-app-uare,babel已经包含在内,因此您可以在代码中使用ES6。