簡體   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