我是React的新手。作为实践,我创建了一个小应用程序。在此过程中,从组件导航到另一个组件时,我传递了一个参数。但是,当我尝试访问路由组件中的此参数值时,将 undefined 作为该值。 为什么我的代码不能与useParams挂钩一起使用,为什么它与useRouteMatch挂钩一起使用?。
我有没有错过useParams的东西?请给我有关如何使用useParam钩子而不是useRouteMatch来获取参数值的建议。两者之间有什么区别?
Body.js
if (this.state.load) {
this.totalPages = this.state.getVal.total_pages;
this.result = this.state.getVal.results.map((item, index) => {
return (
<MovieCard
posterPath={item.poster_path}
movieTitle={item.title}
originalTitle={item.original_title}
movieId={item.id}
key={item.id}
/>
);
});
} else {
this.result = <LinearProgress color="secondary" />;
}
MovieCard.js
import React from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import MovieProfile from './movie-profile/MovieProfile';
const MovieCard = (props) => {
return (
<div className="column">
<div className="card">
<h3>
<img src={props.posterPath} alt="Avatar" height="200" width="200" />
</h3>
<p>Moview Name: {props.movieTitle} </p>
<p>
Original Title :<Link to={`/movie-profile/${props.movieId}`}>{props.originalTitle}</Link>
<Router>
<Switch>
<Route exact path="/movie-profile/:movieId" component={MovieProfile} />
</Switch>
</Router>
</p>
</div>
</div>
);
};
export default MovieCard;
MovieProfile.js
import React from 'react';
import { useRouteMatch, useParams } from 'react-router-dom';
const MovieProfile = () => {
let { movieId } = useParams();
console.log(movieId);
let match = useRouteMatch({
path: '/movie-profile/:movieId',
strict: true,
sensitive: true,
});
console.log(match);
// const {movieId} = useParams();
// console.log({movieId})
return (
<>
<div>Now showing post {movieId}</div>;<h1>{match.params.movieId}</h1>
</>
);
};
export default MovieProfile;