javascript - 推荐使用 apollo 存储的哪种方式,读取片段/读取查询或使用组件中的 graphql hoc 连接查询或传递道具?
问题描述
我们正在使用react-apollo
它,它graphql HOC
在我们的项目中。此外,我们使用PureComponent
fromreact
来确保每次父组件重新渲染时,如果子组件props
没有更改,它不会导致子组件的重新渲染。而对于阅读和写作apollo cache
,我们使用apollo client
.
它graphql HOC
与一个组件挂钩以从服务器检索数据,并将数据存储到缓存中。我们希望将部分数据从缓存中提供给后代组件。
让我们举个例子。在祖先级别,我们从服务器获取项目列表。在儿童级别,我们需要 apollo 商店中已经存在的特定项目的详细信息。
为了做到这一点,有三种可能的方法:
- 将数据作为道具传递给后代组件。
- 这是祖父组件的渲染方法,我们从服务器获取项目列表。
render(){
return (
<ListComponent list={this.props.list}/>
)
}
- 这是列表组件的渲染方法。
render(){
return (
<ItemComponent list={this.props.list} selectedItem={"1"}/>
)
}
- 这是 Item Component 的 render 方法。
render(){
const item = this.props.list[this.props.selectedItem]
return (
<div>{this.props.item}</div>
)
}
- 使用set to钩住
graphql HOC
后代组件。fetch-policy
cache-first
- 这是我们挂钩
graphql query
以获取项目的项目组件。
class ItemComponent extends React.PureComponent {
render(){
return (
<div>{this.props.item}</div>
)
}
}
export default compose(
graphql(QUERY, {
options: ({id}) => ({
variables: {id}
})
}
)
- 使用
apollo client
'readFragment
功能。
render(){
const item = client.readFragment({
id:`List:${this.props.selectedItem}`
fragment:"ListFragment"
});
return (
<div>{this.props.item}</div>
)
}
这三种方法也有相关的优缺点。
第一种方法在每种情况下都适用。唯一的问题是我们通过不必要的道具自上而下地传递数据。
第二种方法在每种情况下都适用。唯一的问题是我们必须不必要地挂钩查询来访问缓存。
第三种方法看起来很干净,但唯一的问题是组件在更新时不会重新渲染,
apollo cache
因为我们使用PureComponent
.
我对这三种方法感到困惑。因此,如果您可以提供关于我应该使用哪种方法的见解,或者如果您可以提供任何其他混合方法,那么这将是一个很大的帮助。
解决方案
推荐阅读
- javascript - 单击 NavItem 以在 React/Materilize 中显示弹出窗口/模态框
- momentjs - 使用 momentjs 计算错误的日期差异
- laravel - Laravel 关系一对多得到结果加入
- blockchain - Corda 节点与派对澄清
- for-loop - 对于范围与静态通道长度 golang
- sql - 列值到 Db2 中的一行,如 Linux 中的 xargs
- azure - 如何使用 LUIS 应用作为知识库来查看我的 Microsoft Azure 语言理解 Web 应用机器人问了哪些问题?
- r - 如何根据先前的行值更新列值?
- java - 在没有 \K 的 Java 正则表达式中替换分隔符内的字符串
- php - 通过 .htaccess 文件将 .php 替换为 .html 扩展名的目的