【发布时间】:2018-09-18 00:17:24
【问题描述】:
目前我必须遍历连接中的现有记录以检查记录是否已经存在,并且只有在不存在时才添加新边缘。我需要这样做的原因是,当页面加载时,commentsContainer 会检索 cmets,但订阅也会获取所有 cmets,这会导致每条评论都被复制。
App.js:
const AppContainer = compose(
lifecycle({
componentDidMount() {
commentSubscription();
},
}),
)(App);
我的订阅:
import { requestSubscription, graphql } from 'react-relay';
import { ConnectionHandler } from 'relay-runtime';
import environment from '../app/environment/environment';
const subscription = graphql`
subscription commentSubscription {
commentAdded {
id
...commentContainer_comment
audio {
id
}
}
}
`;
export default () => requestSubscription(
environment,
{
subscription,
onError: error => console.error(error), // eslint-disable-line no-console
updater: (store) => {
const commentAdded = store.getRootField('commentAdded');
const audioRecord = commentAdded.getLinkedRecord('audio');
const audioId = audioRecord.getValue('id');
const audioProxy = store.get(audioId);
const connection = ConnectionHandler.getConnection(
audioProxy,
'commentsContainer_comments',
);
if (connection) {
const existingRecords = connection.getLinkedRecords('edges');
const recordAlreadyExists = existingRecords.some((existingRecord) => {
const node = existingRecord.getLinkedRecord('node');
const existingId = node.getValue('id');
const commentId = commentAdded.getValue('id');
return existingId === commentId;
});
if (!recordAlreadyExists) {
const edge = ConnectionHandler.createEdge(store, connection, commentAdded, 'CommentPayloadEdge');
ConnectionHandler.insertEdgeBefore(connection, edge);
}
}
},
},
);
评论容器:
import { compose } from 'recompose';
import { graphql } from 'react-relay';
import { fragmentContainer } from 'recompose-relay-modern';
import Comments from './comments';
const fragments = graphql`
fragment commentsContainer_audio on Audio {
id
...commentBoxContainer_audio
comments(
first: $count
after: $cursor
) @connection(key: "commentsContainer_comments") {
edges {
node {
commentId
...commentContainer_comment
}
}
}
}
`;
export default compose(
fragmentContainer(fragments),
)(Comments);
评论容器:
import { compose } from 'recompose';
import { fragmentContainer } from 'recompose-relay-modern';
import { graphql } from 'react-relay';
import Comment from './comment';
const fragments = graphql`
fragment commentContainer_comment on Comment {
id
body
dateAdded
user {
userName
}
}
`;
export default compose(
fragmentContainer(fragments),
)(Comment);
这是使用 Relay 订阅的正确方法吗?必须遍历每条评论以检查它是否已经存在似乎效率低下。
【问题讨论】: