![](/img/trans.png)
[英]What is the correct way to do an async action using redux observable and firebase?
[英]Correct way of dispatching multiple async action in Redux
我想知道分派多个类似类型异步动作的正确方法是什么。 我有一个主页,其中包含四个不同的<Thumbnail />
组件。
<Thumbnail />
组件显示电影列表。 像1st将显示收视率最高的电影,2nd将显示即将上映的电影,依此类推。 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)
})
}
动作.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)
}
动作.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 })
}
};
我认为目前最好的方法是第二种方法,因为这样可以更轻松地处理加载状态(对于所有提取操作,您将获得一致的加载状态,而不是几个单独的微调器)。
一旦获得AsyncMode,将来这可能会有所不同,但是现在,我建议您这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.