代码来源于 http://www.redux.org.cn/docs/advanced/ExampleRedditAPI.html , 其中 fetchPosts
的代码为:
function fetchPosts(subreddit) {
return dispatch => {
dispatch(requestPosts(subreddit))
return fetch(`http://www.reddit.com/r/${subreddit}.json`)
.then(response => response.json())
.then(json => dispatch(receivePosts(subreddit, json)))
}
}
我的理解为执行两次 dispatch
数据操作,第一次为数据请求前数据存储,第二次为数据请求后操作。
引用到的地方为:
dispatch(fetchPostsIfNeeded(selectedSubreddit)),中间用了:
export function fetchPostsIfNeeded(subreddit) {
return (dispatch, getState) => {
if (shouldFetchPosts(getState(), subreddit)) {
return dispatch(fetchPosts(subreddit))
}
}
}
作为包装。
我的疑问是 dispatch
函数参数内容为一个 action obj,那么 fetchPostsIfNeeded
返回的内容为另外一个 dispatch
的 fetchPosts
的函数内容,但是 fetchPosts
return 是一个 fetch
的内容,fetch
返回是一个 promise 的 obj,最终dispatch
返回的是一个 promise obj。我对这个存疑,我也怀疑自己想法不对,所以自己写了一个简单的测试,结果报错,返回错误:
Error: Actions must be plain objects. Use custom middleware for async actions.
以上,我是不是理解不对啊,请各位高手多多指教了,谢谢啊!