为什么使用redux-thunk时,内部函数返回某些内容?

问题描述 投票:0回答:1

我在使用redux-thunk时经常看到代码,内部函数返回某些内容,例如the official Redux async example

The code

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()是重击,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
1个回答
0
投票
[它返回一个promise,允许您在then链中添加回调,并在例如获取subredit帖子时执行某些操作。

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

© www.soinside.com 2019 - 2024. All rights reserved.