问题
I'm just getting going with Apollo GraphQL on a simple React Native app and am really impressed by what it can do. But I'm not quite wrapping my head around how it integrates with the Redux store. Essentially, I need to pass some user input from my searchReducer
into my GraphQL query. I thought I could simply pass the connected component to my GraphQL query and supply a variable, but it's not finding the prop
searchInput
. Here's the code:
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);
I thought that by passing the connect
ed React component, it would find the search
prop
specified by mapStateToProps
. However, it gives:
TypeError: undefined is not an object (evaluating _ref3.search.searchInput).
So obviously it's not finding that prop
. My question is, what is the idiomatic way to use props
from the Redux store as variables in an Apollo GraphQL connected component?
回答1:
To create an answer that goes more into detail and is useful for other users:
To use props from the redux connect
higher order component make sure that the function is applied last. This can be done in your example by
const WithGraphql = graphql(/* ... */)(RepositoryList);
export default connect(mapStateToProps)(WithGraphql);
Alternatively you can use compose
from redux or react-apollo.
Compose applies functions from last to first. For two arguments compose can be written as the following:
compose = (f, g) => (...args) => f(g(...args))
Make sure to list connect first here and then graphql. This creates a new function that you then have to apply to your component RepositoryList
:
export default compose(
connect(mapStateToProps),
graphql(/* ... */),
)(RepositoryList);
来源:https://stackoverflow.com/questions/47915868/how-to-pass-props-from-redux-store-into-apollo-graphql-query