在redux官方文檔里面,針對異步給出的方案是:export function fetchPosts(subreddit) { return function (dispatch) { dispatch(requestPosts(subreddit));//準備發起請求 return fetch(`http://www.subreddit.com/r/${subreddit}.json`) .then(response => response.json()) .then(json => dispatch(receivePosts(subreddit, json)))//拿到請求結果 }}主要思路是:這是一個特殊的action creator(返回了一個function)在這個action creator里面,可以dispatch其他action通過redux-thunk中間件,可以dispatch(fetchPosts('sth'))為什么異步請求不能直接寫在容器組件的mapDispatchToProps里面?感覺1.不用引中間件(redux-thunk、redux-promise)了,也不用考慮中間件執行順序等問題。2.邏輯寫在容器組件里面,感覺沒什么毛病,UI組件如果需要,都可以拿到。
react+redux,異步請求為什么要寫在action creator里面?
翻翻過去那場雪
2019-02-07 14:50:49