如何导航到另一个页面?

问题描述

我从资源 thememoviedb 中获取数据。我收到了一定数量的电影,我也在页面上展示了它们。我尝试去每部电影查看文件 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,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>)}

解决方法

如果您想在 / 路由上显示电影列表,并在 /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> 包装,这意味着它应该始终存在/可见。