reactjs - 反应电影数据库应用程序数据.JSON
问题描述
我正在关注 Roy Derks——React Projects 这本书,我正在研究“创建电影列表应用程序”项目,该项目仅显示 data.JSON。
数据.JSON:
[
{
"id": 1,
"title": "Avatar",
"distributor": "20th Century Fox",
"year": 2009,
"amount": "$2,787,965,087",
"img": {
"src": "media/avatar.jpg",
"alt": "avatar"
},
"ranking": 1
},
{
"id": 2,
"title": "Titanic",
"distributor": "20th Century Fox",
"year": 1997,
"amount": "$2,187,463,944",
"img": {
"src": "media/titanic.jpg",
"alt": "titanic"
},
"ranking": 2
},
{
"id": 3,
"title": "Star Wars: The Force Awakens",
"distributor": "Walt Disney Studios Motion Pictures",
"year": 2015,
"amount": "$2,068,223,624",
"img": {
"src": "media/star_wars_the_force_awakens.jpg",
"alt": "star_wars_the_force_awakens"
},
"ranking": 3
},
{
"id": 4,
"title": "Avengers: Infinity War",
"distributor": "Walt Disney Studios Motion Pictures",
"year": 2018,
"amount": "$2,048,359,754",
"img": {
"src": "media/avengers_infinity_war.jpg",
"alt": "avengers_infinity_war"
},
"ranking": 4
},
{
"id": 5,
"title": "Jurassic World",
"distributor": "Universal Pictures",
"year": 2015,
"amount": "$1,671,713,208",
"img": {
"src": "media/jurassic_world.jpg",
"alt": "jurassic_world"
},
"ranking": 5
}
]
Card.js:
import React from 'react';
const Card = ({ movie }) => {
return (
<div>
<h2> {`#${ movie.ranking } - ${ movie.title } (${ movie.year })`} </h2>
<img src = { movie.img.src } alt={ movie.img.alt } width='200' />
<p> {`Distibutor: ${ movie.distributor }`} </p>
<p> {`Amount: ${ movie.amount }`} </p>
</div>
);
};
export default Card;
List.js
import React, {Component} from 'react';
import Card from '../components/card/Card'
class List extends Component
{
constructor(){
super()
this.state = {
data: [],
loading: true
};
}
async componentDidMount()
{
const movies = await fetch('../assets/data.json');
const moviesJSON = await movies.json();
if(moviesJSON)
{
this.setState({
data: moviesJSON,
loading: false
});
}
}
render()
{
const { data, loading} = this.state;
if(loading)
{
return <div>Loading... </div>
}
return data.map(movie => <Card key = { movie.id } movie = { movie } />);
}
}
export default List;
应用程序.js:
import './App.css';
import List from './containers/List';
function App() {
return (
<div className="App">
<h1>Let's Do it!</h1>
<List />
</div>
);
}
export default App;
输出显示“正在加载......”,我应该得到电影列表。我不知道为什么加载不包含错误值并且应该显示电影列表。我遵循了作者给出的每一条指令。
编辑:仍然无法正常工作,有人可以帮忙吗?
解决方案
一切似乎都很好。你能在 if(moviesJSON) 之前放一个 console.log(moviesJSON)。可能是文件路径不对。您可以使用 f12 键查看控制台输出
推荐阅读
- javascript - Can I have a div that has a parallax image also show the parallax'd image scroll up
- php - 将 API 中的 Json 插入数据库
- android - 更新到最新版本后,您需要在此活动中使用 Theme.AppCompat 主题(或后代)
- rcpp - 无法使用 Eigen 编译旋转 QR 分解(通过 RcppEigen)
- python - 如何在 Flask-Admin 中显示参考字段的实际字段?
- javascript - 带有 jQuery 的 PouchDB
- reactjs - 在反应本机导致错误的注销时清除 redux 存储
- node.js - How to integrate Mongoose and GridFS to NestJS?
- angular - 返回 Observable 的 Angular 服务的单元测试错误部分
- python - 嵌套列表中的最小值