如何从变异中获取新对象的ID?

时间:2015-09-12 13:07:13

标签: javascript reactjs relayjs

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

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

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

E.g。我的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应该是变异创建的对象,但我怎样才能掌握它呢?

1 个答案:

答案 0 :(得分:19)

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

服务器端突变

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回调,但会添加到客户端商店。