Apollo:在订阅更新时更新 React 道具?
Posted
技术标签:
【中文标题】Apollo:在订阅更新时更新 React 道具?【英文标题】:Apollo: Update React Props on Subscription Update? 【发布时间】:2017-11-28 17:22:09 【问题描述】:查看订阅的 Apollo 文档示例代码,我还没有看到如何使用订阅结果更新 React 道具。
来自http://dev.apollodata.com/react/subscriptions.html:
Here is a regular query:
import CommentsPage from './comments-page.js';
import graphql from 'react-apollo';
import gql from 'graphql-tag';
const COMMENT_QUERY = gql`
query Comment($repoName: String!)
entry(repoFullName: $repoName)
comments
id
content
`;
const withData = graphql(COMMENT_QUERY,
name: 'comments',
options: ( params ) => (
variables:
repoName: `$params.org/$params.repoName`
,
)
);
export const CommentsPageWithData = withData(CommentsPage);
Now, let’s add the subscription.
请注意,此示例代码似乎省略了 props
代码的这一部分,用于通常的查询 - 来自 http://dev.apollodata.com/react/queries.html:
props: ( ownProps, data: loading, currentUser, refetch ) => (
userLoading: loading,
user: currentUser,
refetchUser: refetch,
),
...哪个 AFAIK 是更新我的 React 组件上的数据道具并触发页面刷新的正确方法。
这是来自http://dev.apollodata.com/react/subscriptions.html的完整订阅代码示例:
const withData = graphql(COMMENT_QUERY,
name: 'comments',
options: ( params ) => (
variables:
repoName: `$params.org/$params.repoName`
,
),
props: props =>
return
subscribeToNewComments: params =>
return props.comments.subscribeToMore(
document: COMMENTS_SUBSCRIPTION,
variables:
repoName: params.repoFullName,
,
updateQuery: (prev, subscriptionData) =>
if (!subscriptionData.data)
return prev;
const newFeedItem = subscriptionData.data.commentAdded;
return Object.assign(, prev,
entry:
comments: [newFeedItem, ...prev.entry.comments]
);
);
;
,
);
当结果来自非订阅查询COMMENT_QUERY
时,如何获取此处显示的代码,以更新我的 React 组件上的数据道具并触发页面刷新?
【问题讨论】:
【参考方案1】:感谢 Apollo Slack 上的 @neophi 的回答!
const withDataAndSubscription = graphql(GETIMS_QUERY,
options(toID)
console.log(GETIMS_QUERY);
const fromID = Meteor.userId();
return
fetchPolicy: 'cache-and-network',
variables: fromID: `$fromID`, toID: `$toID`
;
,
props: props =>
return
loading: props.data.loading,
instant_message: props.data.instant_message,
subscribeToMore: props.data.subscribeToMore,
subscribeToNewIMs: params =>
const fromID = Meteor.userId();
const toID = params.toID;
return props.data.subscribeToMore(
document: IM_SUBSCRIPTION_QUERY,
variables: fromID: `$fromID`, toID: `$toID`,
updateQuery: (previousResult, subscriptionData) =>
if (!subscriptionData.data)
return previousResult;
const newMsg = subscriptionData.data.createIM;
return update(previousResult,
instant_message:
$push: [newMsg],
,
);
);
;
,
)
;
【讨论】:
import update from 'immutability-helper';
--- https://www.npmjs.com/package/immutability-helper
.
这只是 Obejct.assign(, prev, data) 的另一种方式吗?
我已经有一段时间没有编写代码了——详情请参阅https://www.npmjs.com/package/immutability-helper
。以上是关于Apollo:在订阅更新时更新 React 道具?的主要内容,如果未能解决你的问题,请参考以下文章
使用`react-apollo-hooks`和`useSubscription`钩子时如何避免“自动更新”缓存
每当我的 Apollo 订阅在 React 中被触发时,我如何调用函数?