栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用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,我会修复它。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/397988.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号