【问题标题】:`The 'async' modifier can only be used in TypeScript files.ts(8009)` error when using async in react.js在 react.js 中使用异步时,`'async' 修饰符只能用于 TypeScript files.ts(8009)` 错误
【发布时间】:2020-07-10 02:12:42
【问题描述】:

所以当我尝试在 react 文件中添加 async/await 时,我得到了这个错误:

The 'async' modifier can only be used in TypeScript files.ts(8009)

这是否意味着我不能在 React 中使用 async/await 或者这是 vs 代码的问题,或者我可以做些什么来启用它?

这是整个文件:

import React from 'react'
import Button from 'react-bootstrap/Button'
import {addOrder} from '../actions/orderAction'
import {connect} from 'react-redux'

class Dish extends React.Component{

    async handleClick = (dish) =>{
     this.props.addOrder(dish)
     localStorage.setItem("order", this.props.order)
     alert(`${dish.name} added to your order!`)
    }


    render(){
      let dish = this.props.dish  
        return(
        <div className="col-4">  
            <img />
            <h5>{dish.name}         ${dish.price}</h5>
            <Button onClick = {()=>this.handleClick(dish)} size="sm" variant="primary">Order</Button> 
        </div>
    )
  }
}

const mapDispatchToProps = dispatch =>{
    return {
        addOrder: (dish) =>dispatch(addOrder(dish))
    }
}

const mapStateToProps = state =>{
    return{
        order: state.order
    }
}


export default connect(null,mapDispatchToProps)(Dish)

谢谢!

【问题讨论】:

    标签: javascript reactjs visual-studio-code async-await


    【解决方案1】:

    对于普通函数,我们将 async 关键字放在函数名之前

    async handleClick(dish) {   this.props.addOrder(dish)  
     localStorage.setItem("order", this.props.order)   alert(`${dish.name}
     added to your order!`) }
    

    对于 lambda 函数,我们将 aync 关键字放在参数之前

     handleClick = async (dish) =>{
         this.props.addOrder(dish)
         localStorage.setItem("order", this.props.order)
         alert(`${dish.name} added to your order!`)
        }
    

    【讨论】:

      【解决方案2】:

      你可以试试

      async handleClick(dish) {
        this.props.addOrder(dish)
        localStorage.setItem("order", this.props.order)
        alert(`${dish.name} added to your order!`)
      }
      

      handleClick = async(dish) => {
        this.props.addOrder(dish)
        localStorage.setItem("order", this.props.order)
        alert(`${dish.name} added to your order!`)
      }
      

      【讨论】:

      • 我之前用第二种解决方案解决了这个问题。不过还是谢谢你的回答!
      【解决方案3】:

      你已经在 settings.json 中尝试过这个

      “javascript.validate.enable”:真

      【讨论】:

      • 嗨乔恩!我在哪里可以找到 settings.json?我搜索了它,但在我的文件中的任何地方都没有看到它
      • 我假设这是一个 linting 错误。如果你使用 vs 代码,它应该在 .vs 文件夹中。您可以创建一个名为 settings.json 然后: { "javascript.validate.enable": true }
      • 我找到了,谢谢!然后我将它添加到它,结合它最初的样子,现在它看起来像:``` { "prettier.semi": true, "javascript.validate.enable": true } 但它仍然给了我那个错误,我该怎么办? ```
      猜你喜欢
      • 2020-08-09
      • 1970-01-01
      • 2021-05-02
      • 2020-11-30
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多