【发布时间】:2020-02-29 13:39:16
【问题描述】:
在使用redux-thunk的时候经常看到代码,内部函数返回一些东西,比如the official Redux async example:
const fetchPosts = subreddit => dispatch => {
dispatch(requestPosts(subreddit))
return fetch(`https://www.reddit.com/r/${subreddit}.json`)
.then(response => response.json())
.then(json => dispatch(receivePosts(subreddit, json)))
}
const shouldFetchPosts = (state, subreddit) => {
// return true or false
}
export const fetchPostsIfNeeded = subreddit => (dispatch, getState) => {
if (shouldFetchPosts(getState(), subreddit)) {
return dispatch(fetchPosts(subreddit))
}
}
所以fetchPostsIfNeeded() 是一个thunk,fetchPosts() 也是。它们都返回一个函数,该函数也返回一些东西。现在这个函数实际上是由中间件调用的,我认为返回的值从来没有被使用过。那么为什么 thunk 中的内部函数不断返回一些东西而不是仅仅调用它呢?代码可能是:
const fetchPosts = subreddit => dispatch => {
dispatch(requestPosts(subreddit))
fetch(`https://www.reddit.com/r/${subreddit}.json`)
.then(response => response.json())
.then(json => dispatch(receivePosts(subreddit, json)))
}
const shouldFetchPosts = (state, subreddit) => {
// return true or false
}
export const fetchPostsIfNeeded = subreddit => (dispatch, getState) => {
if (shouldFetchPosts(getState(), subreddit)) {
dispatch(fetchPosts(subreddit))
}
}
【问题讨论】:
标签: reactjs redux redux-thunk