06-19集中处理请求的Orchestra



当我们的组件里请求非常多(比如今天的需求是一个组件里处理12个请求…),给每一个请求都写一遍loading和错误处理等非常繁琐,因此统一管理请求就很有必要了。orchestra原义为交响乐,这里用作统一处理请求的组件名称。
orchestra本质为HOC高阶组件。


使用时需要定义的属性包括type,action,runner和可选的prop,initialParams.


其中,runner代表调用的函数。

type Runner = (...args: any[]) => IterableIterator<any>

以其中一组CRUD为例,564行的runner即调用522行的load函数,返回值赋给this.props.section.最后的585行为初始值。


loading为一个数组,通过toggleLoading函数来判断当前正在加载还是加载完成的状态。



在展示组件内部,则通过数组的some方法选择展示加载组件还是加载后的页面。


错误处理是一个对象,在构造函数里赋空值,在render渲染组件之前的componentWillMount里改变其值。


完整的源码长这样:

import { runSaga, Task as RootTask } from "redux-saga"
import { takeLatest, put } from "redux-saga/effects"
import EventEmitter, { Action } from "./EventEmitter"
import React from "react"

export enum Type {
  INIT,
  BLOCK,
  NON_BLOCK,
}

type Runner = (...args: any[]) => IterableIterator<any>

interface Task<Payloads, Actions extends number> {
  type: Type
  action: Actions
  runner: Runner
  prop?: keyof Payloads
  initParams?: any
}

type RecuPartial<T> = { [key in keyof T]?: RecuPartial<T[key]> }

interface State<T, Actions> {
  results: RecuPartial<T>
  loading: Actions[]
  errors: {
    [key: number]: string
  }
}

function* taskRunner(runner: Runner, props: any, { type, params, onSuccess }: Action<any>) {
  try {
    const payload = yield* runner(props, params)
    yield put({
      type,
      payload,
      onSuccess,
    })
  } catch (err) {
    yield put({ type, err })
  }
}

function connOrchestra<Props, Payloads, Actions extends number>(
  tasks: Array<Task<Payloads, Actions>>,
  initPayloadsState?: RecuPartial<Payloads>,
) {
  return <P extends WithOrchestra<Payloads, Actions>>(Comp: React.ComponentType<P>) => {
    type T = Omit<P, keyof WithOrchestra<Payloads, Actions>> & Props
    return class Orchestra extends React.Component<T, State<Payloads, Actions>> {
      rootTask: RootTask
      emitter: EventEmitter
      currentActions: Actions[]
      constructor(props: T) {
        super(props)

        this.toggleLoading = this.toggleLoading.bind(this)
        this.saga = this.saga.bind(this)
        this.call = this.call.bind(this)

        this.emitter = new EventEmitter()
        this.currentActions = []
        this.state = {
          results: initPayloadsState,
          loading: [],
          errors: {},
        }
      }
      componentWillMount() {
        this.rootTask = runSaga(
          {
            subscribe: cb => this.emitter.addEventListener(cb),
            dispatch: (r: any) => {
              const { type, payload, onSuccess, err } = r
              const task = tasks.find(task => task.action === type)

              if (err) {
                this.setState(({ errors }: any) => ({
                  errors: {
                    ...errors,
                    [task.action]: err.message,
                  },
                }))
              } else {
                if (task.prop) {
                  this.setState(({ results }: any) => ({
                    results: {
                      ...results,
                      [task.prop]: payload,
                    },
                  }))
                }
              }

              this.toggleLoading(task)
              if (onSuccess) {
                onSuccess()
              }
            },
            onError: e => {
              console.error(e) /* tslint:disable-line no-console */
            },
          },
          this.saga,
        )
        for (const task of tasks) {
          if (task.type === Type.INIT) {
            this.call(task.action, task.initParams)
          }
        }
      }
      *saga() {
        for (const { action, runner } of tasks) {
          yield takeLatest(({ type }: Action<any>) => type === action, taskRunner as any, runner, this.props)
        }
      }
      toggleLoading({ action }: Task<Payloads, Actions>) {
        this.setState(({ loading }) => {
          loading = loading.includes(action) ? loading.filter(a => a !== action) : [...loading, action]
          return { loading }
        })
      }
      call(action: Actions, params: any) {
        return new Promise((onSuccess, reject) => {
          if (this.currentActions.includes(action)) {
            reject()
          }
          const task = tasks.find(task => action === task.action)
          if (!task) {
            reject("task not found")
          }
          this.toggleLoading(task)
          this.emitter.dispatch({
            type: action,
            params,
            onSuccess,
          })
        })
      }
      end() {
        this.rootTask.cancel()
      }
      render() {
        const { loading, errors, results } = this.state
        return <Comp {...this.props} loading={loading} errors={errors} {...results} call={this.call} />
      }
    }
  }
}

export default connOrchestra
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,062评论 19 139
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,054评论 3 119
  • 你是否想更快地学习? 无论是在学习一门新语言,一种新的乐器,或是一个新的运动,我们都希望能够竭尽所能地加速学习。但...
    VC就是VC阅读 8,366评论 16 116
  • 在家乡不远的南边 一条小河轻轻地流 水面偶尔荡起水花 风起时 浣纱的姑娘垂下的黑发 飘荡在冬天芦苇编织的暖色里 瞎...
    三玄阅读 4,340评论 0 4
  • 1:早起:6:30起床(大概是天冷的原因,2月份来说,6:30起床比较困难,目标设置的有点过高,当然也是自己意志力...
    A张爽阅读 1,193评论 0 0

友情链接更多精彩内容