【发布时间】: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<AsyncModel>('Async2', {...})。这有意义吗? -
我很欣赏这个建议,但据我所知,您需要在初始化 types.model 时提供类型 - 我不知道那会是什么
-
也许您可以根据需要对其进行修改?codesandbox.io/s/2pvw3r14oj
标签: mobx mobx-state-tree