繁体   English   中英

“类型 {} 上不存在属性 json” TypeScript

[英]“Property json does not exist on type {}” TypeScript

我对 TypeScript 非常陌生,并且有一个项目要在明天完成。 我想要做的是将我的 json 文件导入到 componentDidMount() 并在应用程序上呈现。 我认为我至少在做正确的事情,因为当我通过“响应”进行 hover 时,我在 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 .json() ,因为您的响应已经是您需要的 object 。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM