一个动作可以有一个类型数组,而不是一个类型?

时间:2018-06-06 05:36:26

标签: reactjs react-redux redux-middleware

我在围绕这段代码时遇到了一些麻烦。我会查看某个看起来像这样的中间件:

/* /middleware/api.js  */

export const CALL_API = Symbol('Call API')

export default store => next => action => {

  const callAPI = action[CALL_API]

  // So the middleware doesn't get applied to every single action
  if (typeof callAPI === 'undefined') {
    return next(action)
  }

  let { endpoint, types, authenticated } = callAPI

  const [ requestType, successType, errorType ] = types

  // Passing the authenticated boolean back in our data will let us distinguish between normal and secret quotes
  return callApi(endpoint, authenticated).then(
    response =>
      next({
        response,
        authenticated,
        type: successType
      }),
    error => next({
      error: error.message || 'There was an error.',
      type: errorType
    })
  )
}

好吧,他们正在使用符号,这已经让我有点落后了,但我可以解决这个问题。 (作为一个FYI,callApi方法本质上是一个围绕ajax / fetch调用的包装器。)

对我来说,奇怪的部分是定义的几个动作。该项目使用redux-thunk,因此一些操作返回一个调用dispatch的方法,这不是什么大不了的事,但是我得到的另外两个操作包括一个名为types的数组而不是一个type。以下是其中一个例子:

// actions.js

import { CALL_API } from './middleware/api'

export const QUOTE_REQUEST = 'QUOTE_REQUEST'
export const QUOTE_SUCCESS = 'QUOTE_SUCCESS'
export const QUOTE_FAILURE = 'QUOTE_FAILURE'

// Uses the API middlware to get a quote
export function fetchQuote() {
  return {
    [CALL_API]: {
      endpoint: 'random-quote',
      types: [QUOTE_REQUEST, QUOTE_SUCCESS, QUOTE_FAILURE]
    }
  }
}

而不是拥有type属性,就像我见过的每个操作一样,它有一个名为types的数组?

我无法弄清楚它应该如何运作。减速机就像我所看到的一样香草:

// The quotes reducer
function quotes(state = {
    isFetching: false,
    quote: '',
    authenticated: false
  }, action) {
  switch (action.type) {
    case QUOTE_REQUEST:
      return Object.assign({}, state, {
        isFetching: true
      })
    case QUOTE_SUCCESS:
      return Object.assign({}, state, {
        isFetching: false,
        quote: action.response,
        authenticated: action.authenticated || false
      })
    case QUOTE_FAILURE:
      return Object.assign({}, state, {
        isFetching: false
      })
    default:
      return state
  }
}

那里没有什么花哨的东西。任何人都可以解释看起来非标准操作(没有type属性,但名为types的数组)最终是如何工作的?

0 个答案:

没有答案
相关问题