使用Apollo Client动态设置React组件的GraphQL查询

使用Apollo Client动态设置React组件的GraphQL查询,第1张

使用Apollo Client动态设置React组件的GraphQL查询

让我们以以下组件为例:

ProfileWithData.js

import React, { Component, PropTypes } from 'react';import { graphql } from 'react-apollo';import gql from 'graphql-tag';class Profile extends Component { ... }Profile.propTypes = {  data: PropTypes.shape({    loading: PropTypes.bool.isRequired,    currentUser: PropTypes.object,  }).isRequired,};// We use the gql tag to parse our query string into a query documentconst CurrentUserForLayout = gql`  query CurrentUserForLayout {    currentUser {      login      avatar_url    }  }`;const ProfileWithData = graphql(CurrentUserForLayout)(Profile);

用更高阶的组件将其包装起来非常容易:

Profile.js

import React, { Component, PropTypes } from 'react';export class Profile extends Component { ... }Profile.propTypes = {  data: PropTypes.shape({    loading: PropTypes.bool.isRequired,    currentUser: PropTypes.object,  }).isRequired,};

createProfileWithData.js

import React, { Component, PropTypes } from 'react';import { graphql } from 'react-apollo';import { Profile } from './Profile'export default function createProfileWithData(query) => {  return graphql(query)(Profile);}

然后,您可以像这样使用它:

Page.js

import React, { Component, PropTypes } from 'react';import gql from 'graphql-tag';import createProfileWithData from './createProfileWithData';class Page extends Component {  renderProfileWithData() {      const { textQuery } = this.props;      // Simplest way, though you can call gql as a function too      const graphQLQuery = gql`${textQuery}`;      const profileWithDataType = createProfileWithData(graphQLQuery);      return (        <profileWithDataType />      );  }  render() {    return (<div>     ..     {this.renderProfileWithData()}     ..</div>)  }}Profile.propTypes = {  textQuery: PropTypes.string.isRequired,};

我认为你说对了。

当然,不会收到您的个人资料

props.data.currentUser
,而是
props.data.*
取决于根查询,并且您将根据内容进行适当的处​​理。

注意 :这是直接在Stack Overflow中编写的,因此,如果您遇到任何问题-lmk,我会修复它。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5001802.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-14
下一篇2022-11-14

发表评论

登录后才能评论

评论列表(0条)

    保存