06-19集中处理请求的Orchestra

06-19集中处理请求的Orchestra_第1张图片

06-19集中处理请求的Orchestra_第2张图片

06-19集中处理请求的Orchestra_第3张图片

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


06-19集中处理请求的Orchestra_第4张图片

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


06-19集中处理请求的Orchestra_第5张图片

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

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

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


06-19集中处理请求的Orchestra_第6张图片

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


06-19集中处理请求的Orchestra_第7张图片

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


06-19集中处理请求的Orchestra_第8张图片

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


06-19集中处理请求的Orchestra_第9张图片

完整的源码长这样:

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

interface Task {
  type: Type
  action: Actions
  runner: Runner
  prop?: keyof Payloads
  initParams?: any
}

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

interface State {
  results: RecuPartial
  loading: Actions[]
  errors: {
    [key: number]: string
  }
}

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

function connOrchestra(
  tasks: Array>,
  initPayloadsState?: RecuPartial,
) {
  return 

>(Comp: React.ComponentType

) => { type T = Omit> & Props return class Orchestra extends React.Component> { 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) => type === action, taskRunner as any, runner, this.props) } } toggleLoading({ action }: Task) { 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 } } } } export default connOrchestra

你可能感兴趣的:(06-19集中处理请求的Orchestra)