如何导航到另一个页面?
Posted
技术标签:
【中文标题】如何导航到另一个页面?【英文标题】:How do I navigate to another page? 【发布时间】:2021-09-20 20:21:17 【问题描述】:我从资源主题moviedb 中获取数据。我收到了一定数量的电影,我也在页面上展示了它们。我尝试查看每部电影以查看文件 Movie_Details.js 中的详细信息。在这个文件中,我也从资源中获取数据,但是没有发生过渡,并且在底部绘制了 Movie_Details 组件。如何进入电影详情页面并显示数据?谢谢
App.js
import BrowserRouter as Router, Switch, Route, Link from "react-router-dom";
import Popular_Movies from "./Components/Popular_Movies/Popular_Movies";
import Movie_Detail from "./Components/Popular_Movies/Movie_Detail";
function App()
return (
<div>
<Router>
<Popular_Movies/>
<Route path="/movie/:id" exact>
<Movie_Detail/>
</Route>
</Router>
</div>
);
export default App;
Popular_Movie.js
import React from "react";
import image_api from "../../Services/Service";
import Link from "react-router-dom";
export let Popular_Movie = (name, title, poster_path, vote_average) =>
return (<div className='different_movie'>
<img src=image_api + poster_path className='image'/>
<div className='bottom_different_movie'>
<h3> <Link to=`/movie/:id`>name title vote_average</Link></h3>
</div>
</div>)
Popular_Movies.js
import React, useEffect, useState from "react";
import Popular_Movie from "./Popular_Movie";
export let Popular_Movies = () =>
let popularMovieUrl = `https://api.themoviedb.org/3/tv/popular?api_key=e12a044061e5fe9077c7aee8a5165126&language=en-US&page=1`;
let fetchMovies = async () =>
let response = await fetch(popularMovieUrl)
let data = await response.json()
setPopularMovie(data.results)
useEffect(() =>
fetchMovies()
,[])
return (<div>
popularMovie.length > 0 && popularMovie.map(movie => <Popular_Movie key=movie.id ...movie/>)
</div>)
电影细节
import React, useEffect, useState from "react";
export let Movie_Detail = () =>
let movieUrl = 'https://api.themoviedb.org/3/tv/popular?api_key=e12a044061e5fe9077c7aee8a5165126&language=en-US&page=1'
let [differentMovie, setDifferentMovie] = useState([])
let fetchDifferentMovie = async () =>
let response = await fetch(movieUrl)
let data = await response.json()
setDifferentMovie(data.results)
useEffect(() =>
fetchDifferentMovie()
,[])
return (<div>
differentMovie.title
</div>)
【问题讨论】:
我认为最好从您的问题中删除您的 API 密钥。 【参考方案1】:如果您想在/
路由上显示电影列表,并在/movie/:id
上显示电影详细信息,您的路由器结构应如下所示:
<Router>
... // put navigation component here
<Switch>
<Route path="/" exact>
<Popular_Movies/>
</Route>
<Route path="/movie/:id" exact>
<Movie_Detail/>
</Route>
</Switch>
</Router>
在Movie_Detail
组件中,您需要使用useParams 挂钩提取电影id
const id = useParams();
... // fetch movie details using `id`
了解Switch
的运作方式对您很重要。就像你有if-else
逻辑,它应该决定在匹配某个路径时要渲染哪个组件。请在Basic Routing 上阅读更多内容。
附:您在下面看到流行电影和电影详细信息的原因是因为您的 Popular_Movies
组件调用没有用 <Route>
包装,这意味着它应该始终存在/可见。
【讨论】:
以上是关于如何导航到另一个页面?的主要内容,如果未能解决你的问题,请参考以下文章