【问题标题】:"Property json does not exist on type {}" TypeScript“类型 {} 上不存在属性 json”TypeScript
【发布时间】:2019-11-19 02:16:14
【问题描述】:

我对 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;

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

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

【问题讨论】:

  • 我认为你不需要那个.json()。你试过打印response吗?从错误信息看,response 已经是你需要的对象了。
  • 喜欢打印(响应)?我还没有尝试过@BrunoMonteiro
  • console.log(response)。你也是 Javascript 的新手吗? console.log 是在控制台中打印内容的命令 :)
  • 我一定是撞到了头什么的,这就是我的意思,哎呀!
  • 很高兴听到!我将评论作为答案发布,因此您可以接受它,如果可以的话。祝你好运!

标签: javascript json typescript


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 2018-08-17
    • 1970-01-01
    • 2023-02-06
    • 2019-06-28
    • 1970-01-01
    • 2018-11-09
    • 2021-07-11
    • 2019-02-24
    相关资源
    最近更新 更多