如何从突变中获得新对象的ID

How to get the ID of a new object from a mutation?

本文关键字:对象 ID 新对象 突变      更新时间:2023-09-26

我有一个createObject突变,它返回新对象的ID。

返回后,我想重定向到关于新对象的详细页面。

如何使用react/relay从包含组件的突变中获得响应字段?

。我的createObject页面包含如下代码的突变:

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应该是由突变产生的对象,但我如何才能获得它?

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

服务器端突变

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回调可用,但是将不添加到客户端存储。