【发布时间】: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