【问题标题】:Reusing a Mutation in Relay在中继中重用突变
【发布时间】:2016-09-12 23:11:56
【问题描述】:

是否可以重用突变?

假设存在一个突变UpdateItemMutation,我将道具传递给它, 但有时我只想更新一个特定的属性。

即我希望能够做到:

UpdateItemMutation({prop1: 'Data', prop2: 'Data2'})
UpdateItemMutation({prop1: 'Data'})
UpdateItemMutation({prop2: 'Data2'})

不幸的是,我的乐观配置抱怨,因为我传递了一个 undefined 给它。

另外,由于我必须考虑更新所有内容的突变,这将重新查询整个内容,理想情况下更新“prop1”只会对“prop1”执行 fatQuery。

如果 prop 已定义,则使用 @include 似乎在这里不起作用。

【问题讨论】:

  • 你能发布你的变异代码以及你得到的错误吗?

标签: relayjs


【解决方案1】:

目前没有直接的方法可用,尽管有一种解决方法,如果您不介意获取整个项目以响应突变。

当你想更新一个项目的可变数量的属性时,你可以编写一个突变(服务器端),它接受一个属性列表和一个值列表。

// Using `graphql-relay` library's helper function `mutationWithClientMutationId`.
const UpdateItemMutation = mutationWithClientMutationId({
  name: 'UpdateItem',
  inputFields: {
    itemId: { type: new GraphQLNonNull(GraphQLID) }
    properties: { type: new GraphQLList(GraphQLString) },
    values: { type: new GraphQLList(GraphQLString) },
  },
  outputFields: {
    item: {
      type: ItemType,
      resolve: (item) => item,
    },
  },
  mutateAndGetPayload: ({itemId, properties, values, ...args}) => {
    // Iterate over the properties and values.
    // Update the item with itemId.

    return item;
  },
});

客户端突变的调用如下:

Relay.Store.commitUpdate(new UpdateItemMutation({
  item: this.props.item,
  properties: ['prop1', 'prop2'],
  values: ['value1', 'value2'],
}));

关于客户端突变中的乐观更新,您可以从propertiesvalues 制作返回值,即更新后的属性及其值。

据我所知,Relay 目前不支持有条件地在胖查询中包含字段。与 Relay 容器不同,我们不能在 fat 查询中使用变量。看到current efforts by Relay contributors,我相信,在不久的将来,变异 API 会变得更加强大,而且会更加精简。

【讨论】:

    猜你喜欢
    • 2017-07-13
    • 2016-12-10
    • 2017-06-27
    • 2018-02-24
    • 2017-01-21
    • 2016-02-19
    • 2016-05-13
    • 2020-02-28
    • 2016-09-08
    相关资源
    最近更新 更多