我在我的反应应用程序中设置了一个动态路由,当用户单击图像时,它导航到带有 url 的新路由/details/:id
:
<div className='App'>
<Switch>
<Route path='/' exact component={Home} />
<Route exact path='/details/:id' component={ItemDetails} />
</Switch>
</div>
它来自我的功能组件:
const headerImages = (props) => {
const imageResults = props.trending.slice(0, 5).map(r => ( // Grab firt 5 array objects
<Link key={r.id} to={`/details/${r.id}`}>
<div key={r.id}>
<img key={r.id} src={`https://image.tmdb.org/t/p/w1280${r.backdrop_path}`} alt={r.title} className='header-image' />
<h1 className='now-playing'>Latest</h1>
<h1 className='header-title'>{r.title}</h1>
<h4 className='header-details'>{r.overview}</h4>
</div>
</Link>
))
return <div className='header-images'>
<Carousel infinite autoPlay={4500}>{imageResults}</Carousel>
</div>
}
export default headerImages
ItemDetails
是具有 API 调用的基于类的组件,如何将 r.id 值从我的功能组件获取到我的 Api 调用中?
class ItemDetails extends Component {
constructor (props) {
super(props)
this.state = { selectedItem: null }
}
fetchItemDetails = () => {
axios.get('https://api.themoviedb.org/3/movie/${this.props.r.id}?api_key=40d60badd3d50dea05d2a0e053cc96c3&language=en-US')
.then((res) => {
console.log(res.data.results)
})
}
componentDidMount(){
this.fetchItemDetails()
}
render () {
return <h1>test</h1>
}
}
目前 API 调用返回undefined
,但如您所见,我正在尝试将动态 id 传递给调用。
更新的解决方案:
class ItemDetails extends Component {
constructor (props) {
super(props)
this.fetchItemDetails = this.fetchItemDetails.bind(this)
}
fetchItemDetails = (itemId = this.props.match.params.id) => {
axios.get('https://api.themoviedb.org/3/movie/${itemId}?api_key=40d60badd3d50dea05d2a0e053cc96c3&language=en-US')
.then((res) => {
console.log(res.data.results)
})
}
componentDidMount(){
this.fetchItemDetails()
}
render () {
return <h1>test</h1>
}
}
export default ItemDetails