Reactjs 为什么在使用redux thunk时,内部函数会返回一些东西?

Reactjs 为什么在使用redux thunk时,内部函数会返回一些东西?,reactjs,redux,redux-thunk,Reactjs,Redux,Redux Thunk,我经常在使用redux thunk时看到代码,这是一个返回某些内容的内部函数,例如: : 因此,fetchPostsIfNeeded()是一种恶作剧,fetchPosts()也是如此。它们都返回一个函数,函数也返回一些东西。现在这个函数实际上是由中间件调用的,我认为返回的值永远不会被使用。那么为什么thunk内部的函数总是返回一些东西而不是仅仅调用它呢?代码可能是: const fetchPosts = subreddit => dispatch => { dispatch(re

我经常在使用redux thunk时看到代码,这是一个返回某些内容的内部函数,例如:

:

因此,
fetchPostsIfNeeded()
是一种恶作剧,
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))
  }
}

它返回一个承诺,允许您在
然后
链中添加回调,并在获取subredit post时执行某些操作,如示例所示

export const fetchPostsIfNeeded = subreddit => (dispatch, getState) => {
  if (shouldFetchPosts(getState(), subreddit)) {
    dispatch(fetchPosts(subreddit)).then(() => doSomething());
  }
}

您的意思是,
dispatch()
将返回内部函数返回的任何内容?如果是这样,那么它可能是一个功能,有时是有用的。。。但不是在当前的示例中,我尝试在
fetchPosts()
的内部函数中返回
123
,而
fetchPostsIfNeeded()
中的
dispatch()
也在返回
123
。。。所以它看起来只是“无论内部函数想要返回什么”?因此规则是,
dispatch(fn)
将返回任何
fn()
returns,您是对的。看见
export const fetchPostsIfNeeded = subreddit => (dispatch, getState) => {
  if (shouldFetchPosts(getState(), subreddit)) {
    dispatch(fetchPosts(subreddit)).then(() => doSomething());
  }
}