首页 > 解决方案 > 推荐使用 apollo 存储的哪种方式,读取片段/读取查询或使用组件中的 graphql hoc 连接查询或传递道具?

问题描述

我们正在使用react-apollo它,它graphql HOC在我们的项目中。此外,我们使用PureComponentfromreact来确保每次父组件重新渲染时,如果子组件props没有更改,它不会导致子组件的重新渲染。而对于阅读和写作apollo cache,我们使用apollo client.

graphql HOC与一个组件挂钩以从服务器检索数据,并将数据存储到缓存中。我们希望将部分数据从缓存中提供给后代组件。

让我们举个例子。在祖先级别,我们从服务器获取项目列表。在儿童级别,我们需要 apollo 商店中已经存在的特定项目的详细信息。

为了做到这一点,有三种可能的方法:

  1. 将数据作为道具传递给后代组件。
render(){
  return (
    <ListComponent list={this.props.list}/>
  )
}
render(){
  return (
    <ItemComponent list={this.props.list} selectedItem={"1"}/>
  )
}
render(){
  const item = this.props.list[this.props.selectedItem]
  return (
    <div>{this.props.item}</div>
  )
}
  1. 使用set to钩住graphql HOC后代组件。fetch-policycache-first
class ItemComponent extends React.PureComponent {
 render(){
  return (
     <div>{this.props.item}</div>
  )
 }
}
export default compose(
 graphql(QUERY, {
 options: ({id}) => ({
    variables: {id}
  })
 }
)
  1. 使用apollo client'readFragment功能。
render(){
  const item = client.readFragment({
    id:`List:${this.props.selectedItem}`
    fragment:"ListFragment"
  });

  return (
    <div>{this.props.item}</div>
  )
}

这三种方法也有相关的优缺点。

  1. 第一种方法在每种情况下都适用。唯一的问题是我们通过不必要的道具自上而下地传递数据。

  2. 第二种方法在每种情况下都适用。唯一的问题是我们必须不必要地挂钩查询来访问缓存。

  3. 第三种方法看起来很干净,但唯一的问题是组件在更新时不会重新渲染,apollo cache因为我们使用PureComponent.

我对这三种方法感到困惑。因此,如果您可以提供关于我应该使用哪种方法的见解,或者如果您可以提供任何其他混合方法,那么这将是一个很大的帮助。

标签: javascriptreactjsgraphqlapolloreact-apollo

解决方案


推荐阅读