javascript - “属性 json 在类型 {} 上不存在” TypeScript
我对 TypeScript 非常陌生,而且明天就要完成一个项目。我正在尝试的是在 componentDidMount() 中导入我的 json 文件,并在应用程序中渲染它。我觉得我至少做对了一些事情,因为当我悬停在 'response' 上时,我可以看到 JSON 文件中的所有不同键和值。我在将它渲染到我的应用程序上时遇到了麻烦。
这是代码(不要在意 searchField,我稍后会添加,它目前没有报错):
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 的话题,有什么资源或其他建议我可以参考吗?
答案#1
你不需要在那里使用 .json(),因为你的响应已经是你需要的对象。
你可以通过打印响应来测试:console.log(response)