我有一个简单的应用程序,可从本地json文件中检索数据,但我想完成的工作是能够单击列表中的任何电影,并在另一页中显示其描述。我尝试使用react-router,但无法弄清楚。
这是代码:
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 Router做到这一点,实际上非常简单。您需要将路由器设置为使用URL中的电影ID路由到正确的页面。因此,总体思路是这样的:
https://example.net/ -> shows all moves
https://example.net/:id -> shows info for the specific movie ID
您将有2个主要组件: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>
);
}
}
请记住,这是如何完成您要完成的工作的一般性想法。有很多优雅的方法可以编写此代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句