MobX状态树中带有“流”的生成器语法

时间:2018-07-20 21:30:40

标签: javascript ecmascript-6 generator mobx mobx-state-tree

我在MobX状态树存储中有三个操作:第一个从API提取数据,第二个使用数据库中API的数据发送POST请求,第三个获取响应并将其保存到存储中

商店仅由称为列表的这些数据结构的映射组成:

export const ListStore = types
  .model('ListStore', {
    lists: types.map(List),
  })

发送GET和POST请求的前两个动作可以正常工作:

 .actions((self) => ({
    fetchTitles: flow(function* fetchTitles(params: Params) {
      const env = getStoreEnv(self);
      const { clients } = env;
      const browseParams: BrowseParams = {
        category: 'movies',
        imdb_score_min: params.filter.imdbFilterScore,
      };
      let browseResult;
      try {
        browseResult = yield clients.browseClient.fetch(browseParams);
      } catch (error) {
        console.error('Failed to fetch titles', error);
      }
      return browseResult.data.results.map((title) => title.uuid);
    }),
  }))
  .actions((self) => ({
    postList: flow(function* postList(params: Params) {
      const env = getStoreEnv(self);
      const { clients } = env;
      const titles = yield self.fetchTitles(params);
      return clients.listClient.create({
        name: params.name,
        titles,
        invites: params.invites,
        filter: params.filter,
      });
    }),
  }))

但是,当涉及到第三项操作时,实际上将List保存到ListStore中就没有运气了。我已经尝试了很多变体,但根本没有一个起作用。老实说,我对生成器语法不太熟悉,我什至尝试在没有生成器的情况下进行操作。在这里您可以看到我的尝试:

createList: flow(function* createList(params: Params) {
  const env = getStoreEnv(self);
  const list = yield self.postList(params);
  console.log('list in createList', list.data);
  return self.lists.put(List.create({ ...list.data }, env));
  // return self.lists.set(list.id, list.data);
}),
createList: flow(function* createList(params: Params) {
  const list = yield self.postList(params);
  console.log('list in createList', list.data);
  yield self.lists.set(list.id, list.data);
}),
createList(params: Params) {
  return self.postList(params).then((list) => {
    console.log('list in createList', list.data);
    self.lists.set(list.id, list.data);
  });
},
createList: flow(function* createList(params: Params) {
  yield self.postList(params).then((list) => {
    console.log('list in createList', list.data);
    return self.lists.set(list.id, list.data);
  });
}),

我尝试同时使用.set().put(),但无济于事。我也尝试使用yieldreturn ...似乎没有任何作用。 console.log('list in createList', list.data);中记录的数据看起来正确并且与模型匹配(如果不正确,我不会这样说吗?)。没有错误记录到控制台,它只是默默地失败。

如果您能找到错误并查看应如何写,我将非常感谢。谢谢!

1 个答案:

答案 0 :(得分:0)

事实证明问题不在于语法:正如您在MST的维护者的第一条评论中看到的那样,第二个版本是正确的。

问题在于创建模型(此处未显示)的方式。

相关问题