10

I have a createObject mutation that returns the ID of the new object.

After it returns I want to redirect to a detail page about the new object.

How can I get response fields from a mutation in the containing component using react/relay?

E.g. my createObject page contains the mutation with code like:

var onFailure = (transaction) => {

};

var onSuccess = () => {
  redirectTo('/thing/${newthing.id}');   // how can I get this ID?
};

// To perform a mutation, pass an instance of one to `Relay.Store.update`
Relay.Store.update(new AddThingMutation({
  userId: this.props.userId,
  title: this.refs.title.value,
}), { onFailure, onSuccess });
}

newthing should be the object created by the mutation, but how can I get hold of it?

4

1 回答 1

19

通常我们会配置突变的客户端,RANGE_ADD并从突变的服务器端返回一个新thingEdge的,但是在这里您没有客户端上的范围来添加新节点。要告诉 Relay 获取任意字段,请使用REQUIRED_CHILDRENconfig.

服务器端突变

var AddThingMutation = mutationWithClientMutationId({
  /* ... */
  outputFields: {
    newThingId: {
      type: GraphQLID,
      // First argument: post-mutation 'payload'
      resolve: ({thing}) => thing.id,
    },
  },
  mutateAndGetPayload: ({userId, title}) => {
    var thing = createThing(userId, title);
    // Return the 'payload' here
    return {thing};
  },
  /* ... */
});

客户端突变

class AddThingMutation extends Relay.Mutation {
  /* ... */
  getConfigs() {
    return [{
      type: 'REQUIRED_CHILDREN',
      // Forces these fragments to be included in the query
      children: [Relay.QL`
        fragment on AddThingPayload {
          newThingId
        }
      `],
    }];
  }
  /* ... */
}

示例用法

var onFailure = (transaction) => {
  // ...
};

var onSuccess = (response) => {
  var {newThingId} = response.addThing;
  redirectTo(`/thing/${newThingId}`);
};

Relay.Store.update(
  new AddThingMutation({
    title: this.refs.title.value,
    userId: this.props.userId,
  }), 
  {onSuccess, onFailure}
);

请注意,您使用此技术查询的任何字段都将可用于onSuccess回调,但不会添加到客户端存储中。

于 2015-09-13T04:49:57.813 回答