React Apollo:突变后存储更新,但 ui 不反映变化

React Apollo: Store updates after mutation but the ui does not reflect the change

我创建了一个具有以下架构的 graphQL 服务器:

...
#charts interface
interface Chart {
  id: String!
  sql: String!
  title: String
  type: String!
  display: String!
}
type Layout{
  # Unique layout id
  id: String
  # The title displayed on the layout tab
  title: String
  # List of displayed charts
  charts: [Chart]
}
...

在我的客户端上,我有一个 <SummaryLayout/> 组件,其中包含以下 gql 查询:

gql`{
layout(id:"summary"){
  title
  charts {
    id,
    title,
    type,
    display
  }
}}`

加载页面时,布局组件将所有图表显示为页面上的网格。用户稍后可以添加新图表,所以我有 2 个突变:一个创建图表,另一个将新图表添加到布局中:

const addToLayout = gql`
mutation addToLayout($layoutID: String!, $chartID: String!) {
  addToLayout(layoutID: $layoutID ,chartID:$chartID){
    id
    charts {
      id
      sql
      title
      type
      display
    }
  }
}`;

const addChart = gql`
mutation addChart($chartConfig:ChartConfig!) {
  addChart(chartConfig:$chartConfig){
    id
    display
  }
}`;

this.props.addChart({
    variables: {chartConfig: chartConfig}
    }).then((response) => {
       const chartID = response.data.addChart.id;
       console.log("Chart added, DB ID:", chartID);
       this.props.addToLayout({
            variables: {layoutID: "summary", chartID: chartID},
            update: (store, data) => {
              console.log("STORE:",store);
            }
          }).then((response) => {
            appState.toggleDialog(false);
          })
     });

当我登录商店时,我可以看到 Layout:summary 条目已更新,但未反映在 UI 中,弹出的另一件事是还有另一个名为 $ROOT_QUERY.layout({"id":"summary"}) 未使用新数据更新:

我错过了什么?

From the docs:

By default, InMemoryCache will attempt to use the commonly found primary keys of id and _id for the unique identifier if they exist along with __typename on an object.

If id and _id are not specified, or if __typename is not specified, InMemoryCache will fall back to the path to the object in the query, such as ROOT_QUERY.allPeople.0 for the first record returned on the allPeople root query. That would make data for given type scoped for allPeople query and other queries would have to fetch their own separate objects.

A​​pollo 使用生成的密钥来确定在您的突变解决后要更新的内容。归结为您的查询和突变都需要包含 id。这样,两者使用的生成密钥将是相同的。在您的代码中,突变似乎包含布局的 ID,但查询不包含。

如果由于某种原因,id 不可用,您可以使用 dataIdFromObject 选项来确定要关闭的不同字段。