【发布时间】:2018-06-03 14:15:35
【问题描述】:
我刚刚开始在一个简单的 React Native 应用程序上使用 Apollo GraphQL,它的功能给我留下了深刻的印象。但我并没有完全理解它是如何与 Redux 商店集成的。本质上,我需要将一些用户输入从我的searchReducer 传递到我的 GraphQL 查询中。我以为我可以简单地将连接的组件传递给我的 GraphQL 查询并提供一个变量,但它没有找到 prop searchInput。代码如下:
import React, { Component } from 'react';
import { FlatList, Text, StyleSheet } from 'react-native';
import { connect } from 'react-redux';
import Repository from './Repository';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
const query = gql`
query repositoryOwner($login: String!) {
repositoryOwner(login: $login) {
url,
avatarUrl(size: 100),
repositories(first: 5) {
nodes {
name,
description
}
}
}
}`;
class RepositoryList extends Component {
renderItem = ({ item }) => {
return <Repository name={item.name} description={item.description} />;
}
render() {
const { repositoryOwner } = this.props.data;
const data = repositoryOwner ? repositoryOwner.repositories.nodes : [];
return (
<FlatList data={data}
renderItem={(repo) => this.renderItem(repo)} keyExtractor={(item, index) => index} />
);
}
}
const mapStateToProps = (state) => {
return {
search: state.searchReducer
};
};
const withStore = connect(mapStateToProps)(RepositoryList);
export default graphql(query, {
options: ({ search: { searchInput }}) => ({ variables: { login: searchInput }})
})(withStore);
我以为通过connected React 组件,它会找到mapStateToProps 指定的search prop。但是,它给出了:
TypeError: undefined is not an object(评估 _ref3.search.searchInput)。
显然它没有找到prop。我的问题是,使用 Redux 商店中的 props 作为 Apollo GraphQL 连接组件中的变量的惯用方式是什么?
【问题讨论】:
-
先在组件上使用graphql,再连接。这种方式连接道具将被注入到查询包装器中。
-
这似乎行得通!谢谢您的帮助。我的一个担忧是我尝试使用 Apollo 的
composeAPI:apollographql.com/docs/react/basics/setup.html#compose,但它似乎没有使用props。一直抱怨无法将类调用为函数。关于正确使用compose有什么想法吗?
标签: react-native graphql react-apollo apollo-client