我正在构建一个React前端,它允许用户从静态查询列表中选择“活动”查询,并展平到要在表格中显示的结果。将GraphQL查询从更高阶组件传递到嵌套子组件的最佳方法是什么?
我见过的大多数文档/解决方案都专注于将动态条件从组件状态绑定到组件的静态查询,这对我的目的不起作用,因为不同的静态查询具有不同的字段并查询不同的节点类型。
这里的最佳做法/推荐方法是什么?我觉得这不是一个非常独特的用例,但我似乎找不到任何类似的例子。
我正在使用Apollo-Client / Redux作为我的客户端商店。
以下是该组件的粗略轮廓:
class GridViewPage extends React.Component{
constructor(props, context) {
super(props, context);
this.state = {
activeQuery = ... Stores the selected query ...
};
}
render() {
return (
<div className="gridContainer">
...Component here allows users to select a query from active list and saves it/it's ID/Index to the state...
<Panel collapsible>
...Some toolbar components...
</Panel>
...Component here displays the result of the query (Ideally by receiving the query or the result of as a prop?)...
</div>
);
}
}
GridViewPage.propTypes = {
grids: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired
};
function mapStateToProps(state, ownProps) {
return {
// Receives list of available queries as a prop
grids: state.grids
};
}
答案 0 :(得分:3)
我们来看,例如,以下组件:
<强> ProfileWithData.js 强>
> var a = (0);
< undefined
> a
< 0
很容易包装它
<强> Profile.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 document
const CurrentUserForLayout = gql`
query CurrentUserForLayout {
currentUser {
login
avatar_url
}
}
`;
const ProfileWithData = graphql(CurrentUserForLayout)(Profile);
<强> createProfileWithData.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,
};
然后你会像这样使用它:
<强> Page.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);
}
我认为你明白了。
当然,您的个人资料不会收到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
,具体取决于根查询,您可以根据内容对其进行适当处理。
注意:这是直接在Stack Overflow中编写的,所以如果你遇到任何问题 - lmk我会修复它。