我在同一页面上有2个反应组件,
我无法找到根据组件2订阅结果更新组件1结果的方法。
COMPONENT1:
class Comp1 extends React.Component {
render() {
return (
<div>
{this.props.data.loading? <span>loading…</span>
: <span> //show the list of users </span> }
</div>
);
}
}
export default graphql(queryAllUsers)(Comp1) ;
组件2:
class Comp2 extends React.Component {
constructor(props) {
super(props);
this.state = {
newUserCreated: false
}
}
subscribeToNewUser() {
this.subscription = this.props.data.subscribeToMore({
document: subscribeToNewUsersQuery,
variables: {// },
});
}
render() {
return (
<div>
{this.state.newUserCreated}
</div>
);
}
}
答案 0 :(得分:3)
解决方案是使用reducer函数查询第一个组件:
class Comp1 extends React.Component {
render() { ... }
}
export default graphql(queryAllUsers, {
options: (ownProps) => {
return ({
variables: { ...
},
reducer: (previousResult, action) => {
if (action.type === "APOLLO_SUBSCRIPTION_RESULT" && action.operationName === "subscribeToNewUsersQuery") {
//update the previousResult
return previousResultWithNewData;
} else return previousResult;
})
}
})(Comp1);
&#13;
答案 1 :(得分:2)
我想最简单的方法是在第一个组件中使用查询,并通过subscribeToMore
函数添加订阅。
看起来像这样:
...
subscribeToNewUser() {
this.subscription = this.props.queryAllUsers.subscribeToMore({
document: subscribeToNewUsersQuery,
variables: { /* your variables */ },
updateQuery: (previousResult, { subscriptionData }) => {
const changedItem = subscriptionData.data.<subscriptionName>;
if (changedItem !== undefined && changedItem !== null) {
return // update previous result
}
return previousResult;
},
});
}
...
export default graphql(queryAllUsers, {
name: "queryAllUsers"
})
...
(Comp1)
&#13;
其中您具有将在订阅事件中调用的updateQuery
功能。当结果数据良好时,您可以更新商店,例如将新值推送到users数组