【问题标题】:How To Pass Props From Redux Store into Apollo GraphQL Query如何将 Redux Store 中的 Props 传递到 Apollo GraphQL 查询中
【发布时间】: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 的 compose API:apollographql.com/docs/react/basics/setup.html#compose,但它似乎没有使用 props。一直抱怨无法将类调用为函数。关于正确使用compose 有什么想法吗?

标签: react-native graphql react-apollo apollo-client


【解决方案1】:

要创建更详细且对其他用户有用的答案:

要使用来自 redux connect 高阶组件的道具,请确保最后应用该函数。这可以在您的示例中通过

const WithGraphql = graphql(/* ... */)(RepositoryList);

export default connect(mapStateToProps)(WithGraphql);

您也可以使用 reduxreact-apollo 中的 compose。 Compose 从最后到第一个应用函数。对于两个参数,compose 可以写成如下:

compose = (f, g) => (...args) => f(g(...args))

确保先在此处列出连接,然后再列出 graphql。这将创建一个新函数,然后您必须将其应用于您的组件RepositoryList

export default compose(
  connect(mapStateToProps),
  graphql(/* ... */),
)(RepositoryList); 

【讨论】:

  • 就在@Herku。对我来说就像一个魅力。我想我将connect 第二次传递到我的compose 中,这把事情搞砸了。感谢您花时间写一个深思熟虑的答案!
  • 感谢您的解决方法!但这看起来确实是一个错误,所以我还打开了一个问题 here
猜你喜欢
  • 2019-05-09
  • 2018-06-24
  • 2019-04-02
  • 2018-11-06
  • 2018-08-16
  • 2020-11-12
  • 2018-02-27
  • 1970-01-01
  • 2020-09-12
相关资源
最近更新 更多