热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

使用ApolloClient动态设置React组件

让我们以以下组件为例:

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 document
const CurrentUserForLayout = gql`
query CurrentUserForLayout {
currentUser {
login
avatar_url
}
}
`;
const ProfileWithData = graphql(CurrentUserForLayout)(Profile);

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

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

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

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

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 (

);
}
render() {
return (


..
{this.renderProfileWithData()}
..
)
}
}
Profile.propTypes = {
textQuery: PropTypes.string.isrequired,
};

我认为你说对了。

当然,不会收到您的个人资料props.data.currentUser,而是props.data.*取决于根查询,并且您将根据内容进行适当的处​​理。

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





推荐阅读
author-avatar
曦雯天使
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有