创建侦听所有操作错误的React中间件

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

我正在编写我的第一个自定义中间件,对于正在发生的事情略显无能为力。我的目标是检查是否有任何操作收到网络错误,如果是这样的话。

import { Middleware, MiddlewareAPI, Dispatch, Action } from "redux"

export const logger: Middleware = <S>(api: MiddlewareAPI<S>) => (
  next: Dispatch<S>
) => <A extends Action>(action: A): A => {
  console.log("Before")
  const result = next(action)
  if (action.type.HTTPStatus) {
    console.log("HERE IS AN ERROR")
  }

  console.log("After", api.getState())
  return result
}

action.type.HTTPStatus不起作用。我一直在尝试根据action.type过滤操作,但我不知道该怎么做。似乎我对action.type.w的所有内容都没有破坏任何东西,但也没有做任何事情。以下是API操作的示例。

export const getTelevisionChannels = (televisionIds: string[]) => async (
  dispatch: Dispatch<AppState>
) => {
  try {
    const response = await API.post(
      "/Channels/querys/status",
      { body: JSON.stringify({ televisionIds }) },
      true,
      dispatch
    )
    const televisionChannels = await response.json()
    televisionChannels.map((televisionChannel: any) =>
      dispatch(
        getChannelsSuccess(televisionChannel.televisionId, televisionChannel.channels)
      )
    )
  } catch (err) {
    dispatch(push("/404"))
    console.log(err)
  }
}

我确实有一个目标是使用一个单独的Dispatch组件来处理这个错误,它有自己的reducer和action,但首先我需要能够使这个中间件工作。

typescript redux react-redux middleware
1个回答
1
投票

我最近写了一个apiMiddleware,所以这里是简化版。您想要的是在出现API问题时获取错误,然后发送错误操作{ type: errorType }。然后,您需要一个reducer来处理这些更改。

export default function createApiMiddleware(axios) {
  return ({ getState }) => next => action => {
    const api = action[CALL_API]
    if (!api) {
      return next(action)
    }

    const obj = {}
    const { actionPrefix, types, method, host, url, onSuccess, ...props } = api
    const prefix = actionPrefix || ''
    const [startedType, successType, errorType] = types ? types : ACTION_KEYS.map(v => prefix + v)

    next({ type: startedType })

    obj.method = method || 'get'
    obj.url = host ? (host + url) : url

    const onSuccessOps = Object.assign({}, defaultOnSuccess, onSuccess)
    const { responseBody } = onSuccessOps

    const afterSuccess = (payload) => {
      const { customActions } = onSuccessOps
      customActions.forEach(type => {
        next({ type, payload })
      })      
    }

    return axios(
      Object.assign(obj, { ...props })
    ).then(res => {
      const payload = responseBody(res)      
      next({ type: successType, payload })
      afterSuccess(payload)
    }, err => {
      next({ type: errorType, payload: err })
    })
  }
}

export default function createApiReducer(actionPrefix, options) {
  const ops = Object.assign({}, defaultOptions, options)
  const initialState = {
    data: [],
    isLoaded: false,
    isLoading: ops.loadOnStart,
    error: null,
  }

  return (state = initialState, action) => {
    const custom = ops.customActions[action.type]
    if (custom) {
      return custom(state)
    }

    switch (action.type) {
      case `${actionPrefix}Loading`:
        return {
          ...state,
          isLoading: true,
          error: null
        }
      case `${actionPrefix}Error`:
        return {
          ...state,
          isLoading: false,
          error: action.payload
        }
      case `${actionPrefix}Success`:
        return {
          ...state,
          isLoading: false,
          isLoaded: true,
          error: null,
          data: action.payload
        }
      default:
        return state
    }
  }
}

由于您需要一个中间件,因此我将其作为参考,通常您只想在任何redux教科书中为一个API分配几个动作。希望这可以帮助。

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