簡體   English   中英

為什么在使用 redux-thunk 時,內部函數會返回一些東西?

[英]Why when using redux-thunk, the inner function returns something?

我經常在使用 redux-thunk 時看到代碼,內部函數返回一些東西,例如在官方的 Redux async 示例中

代碼

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))
  }
}

它返回一個承諾,允許您在then鏈中添加回調並在獲取子編輯帖子時執行某些操作,例如在示例中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM