语法错误:意外的令牌,在异步和等待中为预期的“,”(24:9)

问题描述 投票:0回答:1

最近,我开始学习使用Typescript编写React。我试图用异步和等待来编写动作。但显示错误Unexpected token, expected "," (24:9)

index.js

import axios from "axios";
import { Dispatch } from "redux";
import { ActionTypes } from "./types"

export interface ToDo {
  company_name: string,
  created_at: Date,
  description: string,
  featured: boolean,
    hashid: string,
    location: string,
    remote: boolean,
    term: null,
    title: string,
    updated_at: string,
    url: string
}

export interface FetchTodoActions{
  type: ActionTypes.fetchTodos,
  payload: ToDo[]
}
export const fetchTodos = ({
  return async(dispatch:Dispatch)=> {
     const response = await axios.get<ToDo[]>('https://codepen.io/jobs.json');
      dispatch<FetchTodoActions>({
      type: ActionTypes.fetchTodos,
      payload: response.data
    })
  }
})

package.json:

{
  "name": "react-ts",
  "version": "1.0.0",
  "description": "",
  "keywords": [],
  "main": "src/index.tsx",
  "dependencies": {
    "@babel/plugin-transform-runtime": "7.8.0",
    "@babel/preset-env": "7.8.2",
    "@babel/runtime": "7.8.0",
    "@types/react-redux": "7.1.5",
    "axios": "0.19.1",
    "react": "16.8.4",
    "react-dom": "16.8.4",
    "react-redux": "7.1.3",
    "react-scripts": "2.1.3",
    "redux": "4.0.5",
    "redux-thunk": "2.3.0"
  },
  "devDependencies": {
    "@types/react": "16.8.8",
    "@types/react-dom": "16.8.2",
    "typescript": "3.3.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "babel": {
    "presets": [
      [
        "@babel/preset-env",
        {
          "targets": {
            "browsers": [">0.25%", "not ie 11", "not op_mini all"]
          }
        }
      ],
      "@babel/preset-react"
    ],
    "plugins": ["@babel/plugin-transform-runtime"]
  },
  "browserslist": [">0.2%", "not dead", "not ie <= 11", "not op_mini all"]
}

我正在共享已实现的codeandbox的链接:

https://codesandbox.io/s/ecstatic-river-bpc6y

请帮助我。

async-await react-redux react-typescript
1个回答
2
投票

您应该更改语法,如下所示,返回函数而不是对象:

export const fetchTodos = (()=>{
  return async(dispatch:Dispatch)=> {
     const response = await axios.get<ToDo[]>('https://codepen.io/jobs.json');
      dispatch<FetchTodoActions>({
      type: ActionTypes.fetchTodos,
      payload: response.data
    })
  }
})

如果要使用对象函数,则语法如下:

export const testing = {
  async dispatch (){


    return "dispatch"
  }

}

async function call(){

  let info = await testing.dispatch();
  console.info({info})
}

call();
© www.soinside.com 2019 - 2024. All rights reserved.