我想知道分派多个类似类型异步动作的正确方法是什么。我有一个主页,其中包含四个不同的<Thumbnail />
组件。
<Thumbnail />
组件显示电影列表。就像第一场秀
评分最高的电影,第二名将显示即将上映的电影,依此类推。 API端点几乎相同,除了查询参数有所不同。任何帮助将不胜感激。
方法1
Homepage.js
componentDidMount() {
this.categories = [{
title: "Top Rated Movies",
url: "movie/top_rated",
},
{
title: "Now Playing",
url: "movie/now_playing"
},
{
title: "Upcoming Movies",
url: "movie/upcoming"
},
{
title: "Top Rated TV shows",
url: "tv/popular",
}]
this.categories.forEach(({ url ) => {
this.props.getFeaturedMovies(url)
})
}
Action.js
export const getFeaturedMovies = (url) => {
return async (dispatch) => {
dispatch({ type: REQUEST_ALL_FEATURED_MOVIES })
fetch(`https://api.themoviedb.org/3/${url}?api_key=${API_KEY}`)
.then(res => res.json())
.then(data => dispatch({ type: RECEIVE_ALL_FEATURED_MOVIES, title, payload: data, success: true }))
.catch(error => {
dispatch({ type: RECEIVE_ALL_FEATURED_MOVIES, payload: error, success: false })
})
}
};
方法2
Homepage.js
componentDidMount() {
this.categories = [{
title: "Top Rated Movies",
url: "movie/top_rated",
},
{
title: "Now Playing",
url: "movie/now_playing"
},
{
title: "Upcoming Movies",
url: "movie/upcoming"
},
{
title: "Top Rated TV shows",
url: "tv/popular",
}]
this.props.getFeaturedMovies(this.categories)
}
Action.js
export const getFeaturedMovies = (categories) => {
return async (dispatch) => {
dispatch({ type: REQUEST_ALL_FEATURED_MOVIES })
let featuredMovies = categories.map(async ({ title, url }) => {
let data = await fetch(`https://api.themoviedb.org/3/${url}?api_key=${API_KEY}`)
let response = await data.json()
return {title, data: response.results}
})
let featuredMoviesList = await Promise.all(featuredMovies)
dispatch({ type: RECEIVE_ALL_FEATURED_MOVIES, payload: featuredMoviesList, success: true })
}
};
答案 0 :(得分:0)
我认为目前最好的方法是第二种方法,因为这样可以更轻松地处理加载状态(对于所有提取操作,您将获得一致的加载状态,而不是几个单独的微调器)。
一旦获得AsyncMode,将来这可能会有所不同,但是现在我推荐这样做。