问题描述
一些上下文:我正在开发一个 React JS 应用程序,它从数据库中读取地理点并以各种方式绘制/映射它们.有原始地图和图表直接显示来自数据库的数据,但也有图表和指标涉及对斜率图、图下面积、直方图、欧几里德距离等点的分析.
Some context: I'm developing a React JS app that reads geographic points out of a database and graphs/maps them in various ways. There are raw maps and plots that just show data straight from the database but there are also plots and metrics that involve analysis on the points like slope plot, area under graph, histograms, Euclidean distance etc.
我设置了一个 GraphQL 客户端,用于向我安装了 Apollo-Client 的 React 应用程序提供数据.以下是 GraphQL 响应示例:
I have a GraphQL client set up to feed me data to my react app with Apollo-Client installed. Here's a sample of the GraphQL response:
{
"data": {
"Points": [
{
"pid": 13196,
"x": 251.88491821289062,
"y": 374.1650085449219
},
{
"pid": 13197,
"x": 257.6238708496094,
"y": 374.17498779296875
},
{
"pid": 13198,
"x": 264.04315185546875,
"y": 374.5350036621094
},
...etc
]
}
}
这太棒了!对于至少 2 个不同的数据视图来说,这是正确的形状,Apollo 客户端使用 InMemoryCache
为我缓存了它,而我根本不需要 redux.
This is great! This is the right shape for at least 2 different views on the data, Apollo client caches this for me using InMemoryCache
and I haven't needed redux at all yet.
困境:我需要的一堆图涉及很多可以重用的派生值(就像我可能会在 2 个不同的视图中使用斜率值).我应该在哪里存储派生数据?
Dilemma: A bunch of the plots I need involve a lot of derived values that get reused (like I might use the slope values in 2 different views). Where should I store my derived data?
现在我把所有的计算都塞进了 React render()
方法中,但这似乎不是一个好主意.
Right now I have all the calculations crammed into React render()
methods but that's doesn't seem like a good idea.
选项:
- 将 Redux 用于派生数据,将所有计算放入 reducer 并以某种方式使其与 Apollo graphql 缓存中的内容保持同步.
- 在服务器上进行派生(然后我可以缓存)并通过网络发送原始和派生.更多的网络流量,但更少的客户端计算.
- 每当传入的 graphql 数据发生变化时,继续计算
render()
中的派生值. - 也许是我没想到的……
推荐答案
- Redux 是一个不错的选择 - 关注点/逻辑/数据的分离和良好的可测试性.
- 这取决于最终的缓存命中/未命中率、额外资源/电源的成本 - 我会避免这种情况.
- 渲染不是计算的最佳位置(还有其他生命周期方法).组件可以使用自己的状态(或新的 getDerivedStateFromProps),但只能与子级共享.
- 您可以使用
react context api
或apollo-link-state
来共享数据/方法.您可以尝试类似 observables/mobx 的解决方案.
- Redux can be quite good option - separation of concerns/logics/data and good testability.
- It depends of eventual cache hit/miss ratio, costs of additional resources/power - I would avoid that.
- Render is not optimal place (there're other lifecycle methods) for calculations. Component can use own state (or new getDerivedStateFromProps) but shared with children only.
- You can use
react context api
orapollo-link-state
to share data/methods. You can try observables/mobx-like solutions.
我还会避免对数据更新进行所有可能的自动重新计算.借助组件/生命周期/上下文,您可以准备(缓存和共享)真正需要使用的派生数据.
I would also avoid automatic all possible recalculations on data updates. With components/lifecycles/contexts you can prepare (cache and share) derived data when it really will be used.
这篇关于Apollo GraphQl 存储派生数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!