我在react应用程序中设置了一条动态路由,当用户单击图像时,它将导航到具有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调用返回未定义,但是如您所见,我正在尝试将动态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`
答案 0 :(得分:2)
您可以使用: const id = this.props.match.params.id
要获取ID并从该特定ID获取数据。
答案 1 :(得分:1)
这是因为您尚未将其绑定到尝试访问道具的功能。
添加构造函数:
this.fetchItemDetails = this.fetchItemDetails.bind(this);
,并且网址应使用模板文字`而不是引号'
`https://api.themoviedb.org/3/movie/${itemId}?api_key=40d60badd3d50dea05d2a0e053cc96c3&language=en-US`
答案 2 :(得分:1)
尝试一下:
import React, { Component } from 'react';
import axios from 'axios';
export default class ItemDtails extends Component {
fetchItemDetails = () => {
const itemId = this.props.match.params.id;
const ROOT_URL = 'https://api.themoviedb.org/3/movie';
const API_KEY = 'api_key=40d60badd3d50dea05d2a0e053cc96c3&language=en-US';
axios.get(`${ROOT_URL}/${itemId}?${API_KEY}`).then(res => {
console.log(res.data.results);
});
};
componentDidMount() {
this.fetchItemDetails()
}
render() {
return <div>Test...</div>;
}
}