谁能帮助我理解如何抽象出 apollo graphQL 逻辑,以便在使用 apollo 和 HOC 与使用更现代的<Query>({data, loading})=>(<MyComponent data={data} loading={loading}/>)</Query>
语法之间进行转换?或者,如果我不能这样做,您如何在不是整个页面本身的子组件中使用 HOC?我next-apollo-appsync
用来处理我所有的 graphQL 问题:
import { withAppSyncData } from "next-apollo-appsync";
import AppSyncConfig from "./aws-exports";
const config = {
url: AppSyncConfig.aws_appsync_graphqlEndpoint,
region: AppSyncConfig.aws_appsync_region,
auth: {
type: AppSyncConfig.aws_appsync_authenticationType,
apiKey: AppSyncConfig.aws_appsync_apiKey
}
};
export default withAppSyncData(config);
使用我的 appsync 设置创建 withData 函数后,我使用 withData 函数创建一个 TodosWithData 函数。
import withData from "../../lib/withData";
import gql from "graphql-tag";
import { graphql } from "react-apollo";
const query = gql`
query listTodos {
listTodos {
items {
id
name
completed
}
}
}
`;
const TodosWithData = MyComponent =>
withData(
graphql(query, {
options: {
fetchPolicy: "cache-and-network"
},
props: props => ({ todos: props.data.listTodos ? props.data.listTodos.items : [] })
})(MyComponent)
);
export default TodosWithData;
这个函数将一个 react 组件作为输入,并返回包裹在组件周围的 apollo,我们将可以访问 下的数据this.props.data
,就像我们期望的那样。奇怪的是,我可以让下面的这个愚蠢的组件工作,但前提是它在页面级别 - 如果我将它移动到我从页面加载的组件中,它就不起作用。
import React from "react";
import TodosQuery from "../graphql/components/todos";
class Todos extends React.Component {
render() {
console.log(this.props); //We have access to the apollo payload
return (
<div>
<p>Static Text</p>
</div>
);
}
}
//This is what injects apollo payload into the Todos dumb-component.
export default TodosQuery(Todos);
这是一个工作回购供参考。我得到的实际错误是Cannot read property 'apollo' of undefined
详细说明我的评论,并使用<Query>
语法:
在src/index.js
:
import React from "react";
import withData from "../lib/withData";
import TodosWithData from "../graphql/components/todos";
class App extends React.Component {
render() {
console.log("props: ", this.props);
return (
<div>
<p>Hello World</p>
<TodosWithData />
</div>
);
}
}
export default withData(App);
在src/graphql/components/todos.js
:
import React from "react";
import { Query } from "react-apollo";
import gql from "graphql-tag";
const query = gql`
query listTodos {
listTodos {
items {
id
name
completed
}
}
}
`;
const TodosWithData = () => (
<Query query={query} fetchPolicy="cache-and-network">
{({ loading, error, data: { listTodos } }) => {
if (error) return <div>Error loading todos</div>
if (loading) return <div>Loading...</div>
return (
<div>
<ul>
{listTodos.items.map(todo => (
<li key={todo.id}>{`${todo.name}${todo.completed ? " - DONE" : ""}`}</li>
))}
</ul>
</div>
)
}}
</Query>
);
export default TodosWithData;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句