2

我是mobx-state-tree第一次使用,我试图用它types.model来建模一个泛型类型。我正在尝试使用这个现有的 mobx 代码:

/**
 * Models an Async request / response - all the properties exposed are
 * decorated with `observable.ref`; i.e. they are immutable
 */
class Async<TRequest, TResponse> implements IAsyncProps<TResponse> {
    /**
     * Whether a request is in process
     */
    @observable.ref isRequesting: boolean = false;

    /**
     * (optional) The response received last time a request was run
     */
    @observable.ref response?: TResponse;

    /**
     * (optional) The error received last time a request was run
     */
    @observable.ref error?: string;

    constructor(private process: (request: TRequest) => Promise<TResponse>) {

    }

    @action
    async run(request?: TRequest) {
        try {
            this.isRequesting = true;
            this.response = undefined;
            this.error = undefined;

            const response = await this.process(request);
            this.runSuccess(response);
        } catch (error) {
            this.runError(error);
        }
    }

    @action private runSuccess(response: TResponse) {
        this.response = response;
        this.isRequesting = false;
    }

    @action private runError(error: any) {
        this.error = error.message ? error.message : error;
        this.isRequesting = false;
    }

    @action
    reset() {
        this.isRequesting = false;
        this.response = undefined;
        this.error = undefined;
        return this;
    }
}

我想将它移植到types.model. 我已经做到了这一点:

const Async2 = types.model('Async2', {
    isRequesting: types.boolean,
    response: types.optional(/*types.? what goes here ???*/, undefined),
    error: types.optional(types.string, undefined)
});

但我坚持如何一般地输入响应。我可以处理其余的操作 - 有人知道这是否可能吗?

4

1 回答 1

1

如果您考虑泛型,它们是动态生成的类。所以你可以写一个函数,给定两个泛型类型返回你的模型定义使用它们:)

就像是

函数异步(ReqType,ResType){。返回 t.model({ . Req: ReqType, . Res: ResType . }) }

我还建议您记住该函数,因此如果您再次调用它,它将返回相同的模型类型而无需创建新模型!:)

于 2017-10-15T06:24:33.653 回答