我正在使用 ReactJS 和 TMDb API 制作电影应用程序,我想按类型获取电影,并将它们显示在我的主页中,为此我创建了一个方法initHorrorMovies(),例如:
对https://developers.themoviedb.org/3/discover/movie-discover类型的电影执行 axios TDMb API 请求
horrorMoviesList用新数据改变状态
问题是有很多类型,所以我要创建与类型一样多的函数和状态。
我正在考虑创建一个movieList对象,该对象将包含每个流派的 tmdb 查询结果以及流派的标题,然后movieList使用该对象更新状态。
你对我有什么建议吗?
我试过这个
class App extends Component {
constructor(props){
super(props);
this.state = {
movieListWithGenre:[],
}
}
componentWillMount() {
this.initGenreMovie();
}
initGenreMovie(){
axios.get(LINK_GENRES).then(function(response){
this.initListMovie(response.data.genres)
}.bind(this));
}
initListMovie(GenreList){
this.setState({ moviesList: this.state.moviesList.push(newMovies)});
GenreList.map((element) => {
axios.get(`${API_END_POINT}discover/movielanguage=en
&with_genres=${element.id}
&include_adult=false&append_to_response=images
&${API_KEY}`).then(function(response){
this.setState({movieListWithGenre:this.state.movieListWithGenre.
push(response.data.results)})
}.bind(this));
})
}
}
编辑
您好,我允许自己返回帖子,因为我开发了一个可行的解决方案,我能够使用 TMDB API 请求获取按流派排序的电影列表。
我的解决方案有效,但在启动应用程序时我有很多延迟,因为我认为程序很繁重,性能受损。
这是我的代码,我可以提供一些改进此代码的提示吗?我提前感谢您的回答。
class App extends Component {
constructor(props){
super(props);
this.state = {
defaultgenre:28,
movieListWithGenre:[],
genreList:[],
genreId:[],
genreTitle:[]
}
}
componentDidMount() {
this.initGenreMovie();
}
initGenreMovie(){
axios.get(`${LINK_GENRES}`).then(function(response){
this.initListMoviesWithGenre(response.data.genres)
}.bind(this));
}
initListMoviesWithGenre(genres){
genres.map((genre) => {
axios.get(`${API_END_POINT}${POPULAR_MOVIES_URL}&${API_KEY}`)
.then(function(response){
let movies = response.data.results.slice(0,14);
let titleGenre = genre.name;
let idGenre = genre.id;
this.setState({movieListWithGenre:[...this.state.movieListWithGenre, movies]});
this.setState({genreTitle:[...this.state.genreTitle, titleGenre]});
this.setState({genreId:[...this.state.genreId, idGenre ]});
}.bind(this));
})
}
render(){
const renderVideoListGenre = () => {
if(this.state.movieListWithGenre) {
return this.state.movieListWithGenre.map((element,index) => {
return (
<div className="list-video">
<Caroussel
key={element.name}
idGenre {this.state.genreId[index]}
movieList={element}
titleList={this.state.genreTitle[index]}
/>
</div>
)
})
}
}
return (
<div>
{renderVideoListGenre()}
</div>
)
}
export default App