GraphQL 入门: Apollo Client - 简介
现在我们已经创建了一个 GraphQL
# 导入需要的组件 import React,{ Component } from 'react'; import PropTypes from 'prop-types'; // React 15.5 只有把React.PropTypes 分离到单独的包中 import { graphql,qql } from 'react-apollo'; // 定义一个普通的React组件 class MyComponent extends Component { render() { return <div>...</div>; } } // 使用`gql`标签初始化GraphQL查询和数据变更 const MyQuery = gql` query MyQuery { todos { text } } `; const MyMutation = gql` mutation MyMutation { addTodo(text: "Test 123") { id } }`; // 数据绑定传入MyQuery和MyComponent,返回一个包含数据的React组件 const MyComponentWithData = graphql(MyQuery)(MyComponent); // 返回一个包含数据更新的React组件 const MyComponentWithMutation = graphql(MyMutation)(MyComponent); 如果使用 ES2016 decorators,可以这样写: import React,{ Component } from 'react'; import { graphql } from 'react-apollo'; @graphql(MyQuery) @graphql(MyMutation) class MyComponent extends Component { render() { return <div>...</div>; } }
该配置对线可以包含一个或多个下面的选项:
withApollowithApollo 让 我们把 import React,{ Component } from 'react'; import { withApollo } from 'react-apollo'; import ApolloClient from 'apollo-client'; # 创建一个普通的React组件 class MyComponent extends Component { ... } MyComponent.propTypes = { client: React.PropTypes.instanceOf(ApolloClient).isRequired,} const MyComponentWithApollo = withApollo(MyComponent); // or using ES2016 decorators: @withApollo class MyComponent extends Component { ... } 然后我们可通过
withRef如果需要访问被包裹的组件,可以在选项中使用 import React,{ Component } from 'react'; import { graphql } from 'react-apollo'; # 一个普通的React组件 class MyComponent extends Component { ... } # 通过graphql函数返回的组件 const MyComponentWithUpvote = graphql(Upvote,{ withRef: true,})(MyComponent); // 调用返回组件的getWrappedInstance方法可得到MyComponent // MyComponentWithUpvote.getWrappedInstance() returns MyComponent instance compose
import { graphql,compose } from 'react-apollo'; import { connect } from 'react-redux'; export default compose( graphql(query,queryOptions),graphql(mutation,mutationOptions),connect(mapStateToProps,mapDispatchToProps) )(Component); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |