javascript - "Property json does not exist on type {}" typescript

标签 javascript json typescript

我是 TypeScript 的新手,明天要完成一个项目。我想要做的是将我的 json 文件导入 componentDidMount() 并将其呈现在应用程序上。我认为我至少做对了一些事情,因为当我将鼠标悬停在“响应”上时,我在我的 JSON 文件中获得了所有不同的键和值。我无法在我的应用程序上呈现它。

这是代码(不要介意 searchField,我稍后会添加它并且在 atm 上没有错误):

import * as React from "react";
import GameCardList from "../GameCardList";
import logo from "./logo.svg";

export interface IGame {
  Name: string;
  ID: number;
  Slug: string;
}

interface IAppProps {
}

interface IAppState {
  games: Array<IGame>;
  searchfield: string;
}

export class App extends React.Component<IAppProps, IAppState> {
  constructor(props: Readonly<IAppProps>) {
    super(props);
    this.state = {
      games: [],
      searchfield: ""
    };
  }

  componentDidMount() {
    import("../games.json")
      .then( response => response.json())
      //^^where the error is
      .then((users: any) => {this.setState({ games: users}); });
  }

  onSearchChange = (event: { currentTarget: { value: any; }; }) => {
    this.setState({ searchfield: event.currentTarget.value });
  }

  render() {
    const { games, searchfield } = this.state;
    const filteredGames = games.filter(game => {
      return game.Name.toLowerCase().includes(searchfield.toLowerCase());
    });
    return !games.length ?
      <h1>Hello I am Loading!!</h1> :
      (
        <div className="tc">
            <GameCardList games={filteredGames} />
        </div>
      );
  }
}

// tslint:disable-next-line:no-default-export
export default App;

有趣的是,我在我的其他 TS 项目中使用 JSON 文件编写了完全相同的代码,并且运行良好。嗯,我做错了什么?

此外,关于在 typescript 文件中导入 JSON 的主题,我可以遵循任何资源或其他建议吗?

最佳答案

你不需要那里的 .json(),因为你的响应已经是你需要的对象。

您可以通过打印响应来测试:console.log(response)

关于javascript - "Property json does not exist on type {}" typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58925677/

相关文章:

javascript - 从js中的时间戳中提取时间

javascript - Vue 单元测试 : Using Functions imported Incorrectly into a Component

ios - 在 SWIFT 中为 JSON 格式制作字符串(包括 TextView 中的换行符)的最佳方法是什么?

typescript - 没有字符串的提供者

javascript - 无法使用 CSS-Approach 或 JQuery-Apprach 将必需的验证添加到文本区域

javascript - 通过 JQuery .ajax 将数据保存到数据库

arrays - Swift 上的 JSON : Array to String/TextField Text

ios - 如何将用户的当前位置与其他位置进行比较并显示在 UITableView 中?

angular - 如何将 CSS 类应用于 AngularDart 中的另一个组件?

css - 无法为 ng-sidebar 设置背景