如何在新页面中显示JSON的结果



我有一个简单的应用程序,可以从本地json文件中检索数据,但我想实现的是能够点击列表中的任何电影,并在另一个页面中显示其描述。我试着使用react路由器,但无法解决。

这是代码:

App.js

import React, { Component } from "react";
import MovieList from "./data/data.json";
export default class Movie extends Component {
render() {
return (
<div>
<h1>Movies:</h1>
{MovieList.map((movie, i) => {
return (
<div className="movie" key={i}>
<li>{movie.title}</li>
</div>
);
})}
</div>
);
}
}

data.json

[
{
"id": 1,
"title": "Movie 1",
"description": "This is the description for Movie 1"
},
{
"id": 2,
"title": "Movie 2",
"description": "This is the description for Movie 2"
},
{
"id": 3,
"title": "Movie 3",
"description": "This is the description for Movie 3"
}
]

您可以使用react路由器来完成,它实际上非常简单。您需要设置路由器以路由到URL中包含电影ID的右侧页面。所以总的想法是:

https://example.net/ -> shows all moves
https://example.net/:id -> shows info for the specific movie ID 

您将有两个主要组件:Movies,用于渲染所有电影的列表;Movie,用于按ID渲染特定电影的描述。

以下是完成此操作的代码以及沙箱链接:https://codesandbox.io/s/brave-dirac-8sdmj?file=/src/App.js

import React, { Component } from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
const MovieList = [
{
id: 1,
title: "Movie 1",
description: "This is the description for Movie 1"
},
{
id: 2,
title: "Movie 2",
description: "This is the description for Movie 2"
},
{
id: 3,
title: "Movie 3",
description: "This is the description for Movie 3"
}
];
class Movies extends Component {
render() {
return (
<div>
<h1>Movies:</h1>
{MovieList.map((movie, i) => {
return (
<div className="movie" key={i}>
<li>
<a href={"/" + movie.id}>{movie.title}</a>
</li>
</div>
);
})}
</div>
);
}
}
const Movie = (props) => {
const {id} = props.match.params;
const movie = MovieList.find(item => item.id === parseInt(id))
return <div>Movie info: {movie.description}</div>;
};
export default class extends Component {
render() {
return (
<Router>
<Switch>
<Route exact path="/">
<Movies />
</Route>
<Route
exact
path="/:id"
render={(props) => <Movie {...props} isAuthed={true} />}
/>
</Switch>
</Router>
);
}
}

请记住,这是一个关于如何完成你想要完成的事情的总体想法。有更优雅的方法来编写此代码。

最新更新