在React组件中使用Async await会导致语法错误。

4

我正在尝试使用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;

Package.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/await代码,但似乎并没有起作用。有人知道我做错了什么吗?

https://babeljs.io/docs/plugins/transform-async-to-generator/ - DanilGholtsman
可能是unexpected-token-in-react-component的重复问题。 - Shubham Khatri
不要在类成员函数中使用 const,如果您错过了插件,请检查重复项,第三,请使用正确的类语法 callApi = async () => { - Shubham Khatri
2个回答

2
async callApi() {
...
}

callApi = async function() {
...
}

在类成员函数前面,不应该使用const关键字。


0

你有:

async () {
    // ...
}

但它应该是:

async () => {
    // ...
}

此外,您需要将它从类声明中取出。目前,您正在尝试将其声明为类的属性或方法,但是类方法声明不使用const或赋值等语句。所以只需在类声明之前将其移到上面即可。
const callApi = async () => {
    // ...
};
export default class App extends React.Component {
    // ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接