作者:曦雯天使 | 来源:互联网 | 2023-07-26 18:56
让我们以以下组件为例:
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,我会修复它。