【发布时间】:2019-09-13 21:39:23
【问题描述】:
Bonjour tout le monde,我尝试使用电影数据库 API 使用 React 按类别进行过滤。 我已经提出了一个请求,我制作了一个 .map 来显示所有按受欢迎程度排序的电影。 我有一个“流派”组件,其中我获取流派名称和“TopFilms”组件,它是“流派”组件的父级,它显示所有按受欢迎程度排名的电影。 所以我在“TopFilms”组件中有一个“getFilms”请求,在“Genres”组件中有一个流派名称的请求。 我希望当我点击“Genres”组件的其中一个类型时,getFilms 函数和“TopFilms”组件将更新为相应的类型。
这是我的 TopFilms 组件(我删除了一些内容以提高可读性):
- 我的所有电影按人气排名的网址:
const baseUrlDiscover = `https://api.themoviedb.org/3/discover/movie?api_key=${process.env.REACT_APP_MOVIE_DB_API_KEY}&sort_by=popularity.desc&language=en-US`;
- 我的构造函数、函数 getFilms() 和 updateCurrentCategory() 用于更新类型:
constructor(props){
super(props);
this.state = {
films: [],
page: 1,
loading: false,
genres: [],
currentCategory: null
};
this.getFilms = this.getFilms.bind(this)
this.btnClickPrev = this.btnClickPrev.bind(this)
this.btnClickNext = this.btnClickNext.bind(this)
}
getFilms(categoryId= ''){
const { page } = this.state
this.setState({
films: [],
loading: true,
})
Axios.get(`${baseUrlDiscover}&page=${page}&with_genres=${categoryId}`)
.then((response) => {
this.setState({
films: response.data.results,
loading: false
})
})
.catch(error => {
console.log(error)
this.setState({
films: [],
loading: false
})
})
}
updateCurrentCategory = (id) => {
this.setState({currentCategory: id})
}
- 我的 componentDidMount() 和 getFilms() 函数(我想我必须添加一个 componentDidUpdate,但最后一个出现“超出最大更新深度”错误..):
componentDidMount(){
this.getFilms()
}
- 在渲染中,有.map来显示所有电影:
const theMovies = this.state.films.map((film) => {
return(
<Grid key={film.id} item xs={6} sm={6} md={3} lg={3}>
<Card className='container-card-poster'>
<CardImg className={classes.cardIaamge} top width="100%" src={`${posterUrl}${film.poster_path}`} alt="Card image cap" />
<figcaption className='fig-caption'>
<h4 className={classes.titleOverlay}>{film.title}</h4>
</figcaption>
</Card>
</Grid>
)
})
还有我的“流派”组件:
const genresUrl = `https://api.themoviedb.org/3/genre/movie/list?api_key=${process.env.REACT_APP_MOVIE_DB_API_KEY}&language=en-US`
class Genres extends Component {
constructor(props) {
super(props)
this.state = {
genres: [],
}
}
componentDidMount(){
Axios.get(genresUrl)
.then((response) => {
this.setState({genres: response.data.genres})
})
.catch((err) => console.log(err));
}
render() {
const { classes } = this.props
return (
<PopupState variant="popover" popupId="demo-popup-menu">
{popupState => (
<React.Fragment>
<Button
variant="contained" {...bindTrigger(popupState)}
href=""
target="_blank"
className={classes.navLink}
>
Genres <ExpandMoreIcon className={classes.icons} />
</Button>
<Menu {...bindMenu(popupState)} onClick={popupState.close}>
{
this.state.genres.map((genre) => {
return <AnchorLink key={genre.id} href='#pop'>
<MenuItem className={classes.menuItemGenres} onClick={()=> this.props.updateCurrentCategory(genre.id)}>{genre.name}</MenuItem>
</AnchorLink>
})
}
</Menu>
</React.Fragment>
)}
</PopupState>
)
}
}
对不起,我的英语不是很好,我试图尽可能清楚,并提前感谢您的帮助。 祝你有美好的一天!
【问题讨论】:
标签: javascript reactjs api filtering