【发布时间】:2019-08-10 21:09:04
【问题描述】:
我在 React Native 中使用 react-apollos Query-Component 从我的后端获取数据。
结果如下所示:
[
{
id: 1,
name: 'US Election',
parties: [
{
name: 'democrats',
id: 4,
pivot: {
id: 3,
answers: [
{
id: 13,
question_id: 3,
reason: 'Lorem ipsum',
__typename: "Answer"
},
{
id: 14,
question_id: 5,
reason: 'Lorem ipsum',
__typename: "Answer"
},
],
__typename: "ElectionPartyPivot"
},
__typename: "Party"
},
],
__typename: "Election"
},
{
id: 2,
name: 'Another one',
parties: [
{
name: 'democrats',
id: 4,
pivot: {
id: 7,
answers: [
{
id: 15,
question_id: 7,
reason: 'Lorem ipsum',
__typename: "Answer"
},
{
id: 18,
question_id: 9,
reason: 'Lorem ipsum',
__typename: "Answer"
},
],
__typename: "ElectionPartyPivot"
},
__typename: "Party"
},
],
__typename: "Election"
}
]
现在,当我console.log的结果,第二次选举“Another one”有pivot来自第一个条目US Election。
我认为这是因为 Apollo 内部正在进行规范化(因为双方的 ID 相同)但我不确定如何修复它,因此它不会正常化或正常化它正确.
编辑
我想出了这个解决方案,但它看起来很老套。我现在将选举 ID 与当事方一起获取,并在缓存中创建不同的标识符。我想知道这是否是一种好习惯?
const cache = new InMemoryCache({
dataIdFromObject: object => {
switch (object.__typename) {
case 'Party': return `${object.election_id}:${object.id}`;
default: return defaultDataIdFromObject(object);
}
}
});
const client = new ApolloClient({
uri: config.apiUrl,
cache
});
【问题讨论】:
标签: javascript apollo react-apollo apollo-client