【问题标题】:mobx-state-tree - can types.model be used to model generic types?mobx-state-tree - types.model 可以用来为泛型类型建模吗?
【发布时间】:2017-10-13 16:05:19
【问题描述】:

我第一次使用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)
});

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

【问题讨论】:

  • 我的猜测是interface AsyncModel { isRequesting: boolean, response?: TResponse, error?: string },然后是types.model&lt;AsyncModel&gt;('Async2', {...})。这有意义吗?
  • 我很欣赏这个建议,但据我所知,您需要在初始化 types.model 时提供类型 - 我不知道那会是什么
  • 也许您可以根据需要对其进行修改?codesandbox.io/s/2pvw3r14oj

标签: mobx mobx-state-tree


【解决方案1】:

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

类似

函数异步(ReqType, ResType){ .返回 t.model({ .请求:请求类型, .资源:资源类型 . }) }

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

【讨论】:

    猜你喜欢
    • 2018-10-06
    • 1970-01-01
    • 2021-12-24
    • 2019-09-05
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多