gpt4 book ai didi

javascript - 在 React 组件中使用 Async await 时会出现语法错误

转载 作者:行者123 更新时间:2023-11-29 20:56:53 24 4
gpt4 key购买 nike

我正在尝试在服务器端使用 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: ''
};
}

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;

包.json

{
"name": "client",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server"
},
"dependencies": {
"babel-plugin-syntax-async-functions": "^6.13.0",
"babel-plugin-transform-async-to-generator": "^6.24.1",
"babel-plugin-transform-regenerator": "^6.26.0",
"html-webpack-plugin": "^2.30.1",
"path": "^0.12.7",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"webpack": "^3.11.0",
"webpack-dev-server": "^2.11.1"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1"
},
"proxy": "http://localhost:3000/"
}

.babelrc

{
"presets":[
"es2015", "react"
],

"plugins": ["transform-regenerator",
"syntax-async-functions",
"transform-async-to-generator"]

}

当我使用“yarn start”启动服务器时,我不断收到以下错误

ERROR in ./src/components/App.jsx
Module build failed: SyntaxError: Unexpected token (21:8)

19 | }
20 |
> 21 | const callApi = async () {
| ^
22 | const response = await fetch('/list-repos');
23 | const body = await response.json();
24 |

@ ./src/index.js 11:11-42
@ multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js
Child html-webpack-plugin for "index.html":
1 asset
[0] ./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html 531 bytes {0} [built]
[1] ./node_modules/lodash/lodash.js 540 kB {0} [built]
[2] (webpack)/buildin/global.js 509 bytes {0} [built]
[3] (webpack)/buildin/module.js 517 bytes {0} [built]
webpack: Failed to compile.

我曾尝试使用 babel 插件来转换异步等待代码,但似乎没有用。有人知道我做错了吗?

最佳答案

async callApi() {
...
}

callApi = async function() {
...
}

不能在类成员函数前使用const。

关于javascript - 在 React 组件中使用 Async await 时会出现语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48860583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com