在 MobX-state-tree (MST) 中执行异步操作的推荐方法是使用flow https://mobx-state-tree.js.org/concepts/async-actions,它接受一个生成器函数作为第一个参数,其中每个承诺都应该被产生。
yield表达式具有类型any在打字稿中 https://github.com/Microsoft/TypeScript/issues/2983#issuecomment-230414026,但是有没有办法在MST中自动输入yield表达式呢?
Example
import { flow, types } from "mobx-state-tree";
type Stuff = { id: string; name: string };
function fetchStuff(): Promise<Stuff[]> {
return new Promise((resolve) => {
resolve([
{ id: "1", name: "foo" },
{ id: "2", name: "bar" }
]);
});
}
const Thing = types.model({
id: types.identifier,
name: types.string
});
const ThingStore = types
.model({
things: types.array(Thing)
})
.actions((self) => ({
fetchThings: flow(function* () {
// "stuff" is of type "any"!
const stuff = yield fetchStuff();
self.things.replace(stuff);
})
}));
到发电机 https://mobx-state-tree.js.org/API/#togenerator可用于将 Promise 转换为生成该 Promise 的生成器。这与yield*
代替yield
(可通过设置downlevelIteration to true在 TypeScript 编译器选项中 https://www.typescriptlang.org/docs/handbook/compiler-options.html#compiler-options) 使得 Promise 返回类型得以保留。
import { flow, types, toGenerator } from "mobx-state-tree";
type Stuff = { id: string; name: string };
function fetchStuff(): Promise<Stuff[]> {
return new Promise((resolve) => {
resolve([
{ id: "1", name: "foo" },
{ id: "2", name: "bar" }
]);
});
}
const Thing = types.model({
id: types.identifier,
name: types.string
});
const ThingStore = types
.model({
things: types.array(Thing)
})
.actions((self) => ({
fetchThings: flow(function* () {
// "stuff" is now of type "Stuff[]"!
const stuff = yield* toGenerator(fetchStuff());
self.things.replace(stuff);
})
}));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)