Javascript Async await在React组件中使用时给出语法错误
我正在尝试用服务器端的hapi.js编写一个基本的react应用程序。我对使用webpack和babel很陌生。我的react组件App.jsx如下所示:Javascript Async await在React组件中使用时给出语法错误,javascript,reactjs,async-await,Javascript,Reactjs,Async Await,我正在尝试用服务器端的hapi.js编写一个基本的react应用程序。我对使用webpack和babel很陌生。我的react组件App.jsx如下所示: import React from 'react'; export default class App extends React.Component { constructor(props) { super(props); this.state = { response:
import React from 'react';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
response: ''
};
}
componentDidMount() {
this.callApi()
.then(res => this.setState({ response: res }))
.catch(err => console.log(err));
}
/* Calling hapi.js api endpoint */
const callApi = async () {
const response = await fetch('/list-repos');
const body = await response.json();
if (response.status !== 200) throw Error(body.message);
return body;
}
render() {
return (
<div style={{textAlign: 'center'}}>
<h1>Hello World</h1>
<p className="App-intro">{this.state.response}</p>
</div>);
}
}
export default App;
B.法律改革委员会
{
"presets":[
"es2015", "react"
],
"plugins": ["transform-regenerator",
"syntax-async-functions",
"transform-async-to-generator"]
}
当我使用“纱线启动”启动服务器时,不断出现以下错误
我曾尝试使用babel插件转换异步等待代码,但似乎不起作用。有人知道我做错了什么吗
async callApi() {
...
}
callApi = async function() {
...
}
您不能在类成员函数前面使用常量。您有:
async () {
// ...
}
但它应该是:
async () => {
// ...
}
此外,您需要将其从类声明中去掉。现在,您正试图将其声明为类上的属性或方法,但类方法声明不使用const
或类似的赋值。因此,在声明类之前,只需将其上移
const callApi = async () => {
// ...
};
export default class App extends React.Component {
// ...
}
对于类成员函数,不要使用
const
的可能重复项,请检查重复项以防丢失插件,第三,使用正确的类语法callApi=async()=>{
async () => {
// ...
}
const callApi = async () => {
// ...
};
export default class App extends React.Component {
// ...
}