reactjs - 结构:如何使用 mobx-state-tree 表示搜索输入、搜索查询和搜索结果?
问题描述
我有一个应用程序正在使用mobx-state-tree
,目前有一些简单的商店:
Article
表示一篇文章,可以是通过第 3 方 API 获取的,也可以是内部编写的ArticleStore
包含对文章的引用:{ articles: {}, isLoading: bool }
简单场景
此设置适用于简单的用例,例如基于 ID 获取文章。例如
- 用户导航到
/article/{articleUri}
articleStoreInstance.fetch([articleUri])
返回有问题的文章- ID 在渲染函数中获取,并使用
articleStoreInstance.articles.get(articleUri)
复杂场景
对于更复杂的场景,如果我想根据复杂的查询获取一组文章,例如{ offset: 100, limit: 100, freeTextQuery: 'Trump' }
,我应该:
- 拥有一个全球
SearchResult
商店,仅链接到用户搜索过的文章 - 实例化一个一次性
SearchResult
存储,只要我需要它就可以传递? - 将查询和一般 UI 状态完全排除在商店之外?
我应该补充一点,我想在页面加载之间将文章保留在商店中,以避免一遍又一遍地重新获取相同的内容。
是否有某种标准化的方法来解决这个问题?有什么例子可以看吗?
解决方案
您可能需要一个Search
跟踪以下信息的商店:
- 查询参数(偏移量、限制等)
- 查询结果(最后一次搜索的结果)
- (可选)查询状态(isLoading)
那么为了避免将文章存储在2个地方,查询结果不应该使用Article
model,而是引用Article
model。任何时候查询,实际结果都会保存在现有的 storeArticleStore
中,并且Search
只保存引用:
import { types, getParent, flow } from 'mobx-state-tree'
const Search = types.model({
params: // your own params info
results: types.array(types.reference(Article))
}).views(self => ({
get parent() {
return getParent(self) // get root node to visit ArticleStore
}
})).actions(self => ({
search: flow(function*(params) {
this.params = params // save query params
const result = yield searchByQuery(query) // your query here
this.parent.articleStore.saveArticles(result) // save result to ArticleStore
this.results = getArticleIds(result) // extract ids here for references
})
}))
希望这是您正在寻找的。
推荐阅读
- python - 如何在图中获取所有张量?
- javascript - 如何增加题数和分数
- javascript - 然后需要阻止带有承诺的异步等待
- python - ubuntu上的socket服务器连接不上
- angular - 如何做路由器认证保护?变得可观察
从 AngularFireAuth 然后转换为保护的布尔值 - c - 包含 math.h 库时程序内存不会增加
- php - 空图像时的图像滑块
- algorithm - 六边形图查找是否有一些网格被包围算法
- c# - 在使用具有潜在作用域依赖关系的 Simpleinjector 时处理 Websharper Remoting Singletons 的最佳方法是什么?
- python - 递归循环没有预期的行为