异步action和redux-thunk理解

异步action通常指的就是异步action建立函数html

action建立函数分为同步action建立函数和异步action建立函数react

同步action建立函数(最多见的):git

function requestPosts(subreddit) {
  return {
    type: REQUEST_POSTS,
    subreddit
  }
}

异步action建立函数(若是利用了redux-thunk,也叫thunk action建立函数,经过使用指定的 middleware,action 建立函数除了返回 action 对象外还能够返回函数。这时,这个 action 建立函数就成为了 thunk):github

// 来看一下咱们写的第一个 thunk action 建立函数!
// 虽然内部操做不一样,你能够像其它 action 建立函数 同样使用它:
// store.dispatch(fetchPosts('reactjs'))

export function fetchPosts(subreddit) {

  // Thunk middleware 知道如何处理函数。
  // 这里把 dispatch 方法经过参数的形式传给函数,
  // 以此来让它本身也能 dispatch action。

  return function (dispatch) {  //redux-thunk使得能够dispatch该函数

    // 首次 dispatch:更新应用的 state 来通知
    // API 请求发起了。

    dispatch(requestPosts(subreddit))

    // thunk middleware 调用的函数能够有返回值,
    // 它会被看成 dispatch 方法的返回值传递。

    // 这个案例中,咱们返回一个等待处理的 promise。
    // 这并非 redux middleware 所必须的,但这对于咱们而言很方便。

    return fetch(`http://www.subreddit.com/r/${subreddit}.json`)
      .then(
        response => response.json(),
        // 不要使用 catch,由于会捕获
        // 在 dispatch 和渲染中出现的任何错误,
        // 致使 'Unexpected batch number' 错误。
        // https://github.com/facebook/react/issues/6895
         error => console.log('An error occurred.', error)
      )
      .then(json =>
        // 能够屡次 dispatch!
        // 这里,使用 API 请求结果来更新应用的 state。

        dispatch(receivePosts(subreddit, json))
      )
  }
}

经过使用redux-thunk中间件,使得能够dispacth一个函数,该函数被thunk中间件调用,且该函数的返回值会做为dispatch方法的返回值,该例中最后返回的是一个promisejson

store.dispatch(fetchPosts('reactjs')).then(() => console.log(store.getState()))

像 redux-thunk 或 redux-promise 这样支持异步的 middleware 都包装了 store 的 dispatch() 方法,以此来让你 dispatch 一些除了 action 之外的其余内容,例如:函数或者 Promise。 redux

当 middleware 链中的最后一个 middleware 开始 dispatch action 时,这个 action 必须是一个普通对象。这是 同步式的 Redux 数据流 开始的地方(译注:这里应该是指,你可使用任意多异步的 middleware 去作你想作的事情,可是须要使用普通对象做为最后一个被 dispatch 的 action ,来将处理流程带回同步方式)api

相关文章
相关标签/搜索