【发布时间】:2016-12-14 13:05:00
【问题描述】:
当id 在每次加载时都不同时,我应该如何(重新)查询对象? 我错过了什么?
const {nodeInterface, nodeField} = nodeDefinitions(
(globalId) => {
const {type, id} = fromGlobalId(globalId);
// This id is different every time (if page is reloaded/refreshed)
// How am I suppose to use this id for database query (e.g by id)?
// How do I get "the right ID"? (ID actually used in database)
console.log('id:', id);
// This is correct: "User"
console.log('type:', type);
if (type === 'User') {
// Function that is suppose to get the user but id is useless ..
return getUserById(id);
}
return null;
},
(obj) => {
if (obj instanceof User) {
return userType;
}
return null;
}
);
const userType = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: globalIdField('User'), // Relay ID
_id: { type: GraphQLString }, // MongoDB ID
email: { type: GraphQLString },
name: { type: GraphQLString }
}),
interfaces: [nodeInterface]
});
【问题讨论】:
-
为什么您的
id会在每次重新加载时更改?id由服务器设置,因此它可以(并且应该)在重新加载时保持一致。fromGlobalId函数只是将id字段从getUserById函数返回的对象中取出,并将其与"User"字符串合并 -
@NevilleS 重新加载时不一样..知道可能是什么原因吗?
-
它在哪里“改变”了?你的意思是,在 React 客户端代码中?如果是这样,当您应该使用服务器返回的合法
ids 时,您可能只是在客户端任意发明ids -
@NevilleS 首先它是如何生成全局 ID 的?数据库 ID 是如何到达那里的(我应该能够在数据库查询中检索和使用它)?我给它的只是
id: globalIdField('User')但_id是真正的交易(数据库中的对象ID)。
标签: reactjs relayjs graphql-js