【问题标题】:Why when using redux-thunk, the inner function returns something?为什么在使用 redux-thunk 时,内部函数会返回一些东西?
【发布时间】:2020-02-29 13:39:16
【问题描述】:

在使用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() 是一个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


    【解决方案1】:

    它返回一个承诺,允许您在then 链中添加一个回调,并在获取子编辑帖子时执行某些操作,如在示例中。

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

    【讨论】:

    • 您的意思是,dispatch() 将返回内部函数返回的任何内容?如果是这样,那么它可能是一个有时有用的功能......但在当前示例中没有
    • 我尝试在fetchPosts() 的内部函数中返回123,而fetchPostsIfNeeded() 中的dispatch() 也返回123 ......所以看起来“不管内部函数是什么想回来”?所以规则是,dispatch(fn) 将返回 fn() 返回的任何内容
    • 是的,你是对的。见github.com/reduxjs/redux-thunk#composition
    猜你喜欢
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 2021-08-06
    • 2016-09-25
    • 1970-01-01
    • 2021-09-09
    相关资源
    最近更新 更多