简体   繁体   English

React Apollo:从Component状态动态更新GraphQL查询

[英]React Apollo: Dynamically update GraphQL query from Component state

I have a component that shows results from a GraphQL query using the react-apollo decorator syntax. 我有一个组件,使用react-apollo装饰器语法显示GraphQL查询的结果。 The query accepts a parameter, which I want to set dynamically based on component state. 查询接受一个参数,我想根据组件状态动态设置该参数。

Consider the following simplified example: 请考虑以下简化示例:

import * as React from ‘react’;
import { graphql } from ‘react-apollo’;
import gql from ‘graphql-tag’;

const myQuery = gql`
    query($active: boolean!) {
        items(active: $active) {

        }
    }
`;

@graphql(myQuery)
class MyQueryResultComponent extends React.Component {
    public render() {
        return <div>
            <input type=“checkbox” /* other attributes and bindings */ />
            {this.props.data.items}
        <div>;
    }
}

When the checkbox is clicked I want to resubmit the query, dynamically setting the active attribute in myQuery , based on the state of the checkbox. 单击复选框时,我想重新提交查询,根据复选框的状态动态设置myQueryactive属性。 I've omitted the handler and bindings of the checkbox for brevity, but how can I cause the query to be re-submitted upon a state change? 为简洁起见,我省略了复选框的处理程序和绑定,但是如何在状态更改时重新提交查询?

Create a new component which will have the prop active passed from a parent component. 创建一个将有一个新的组件prop 主动从父组件传递。

This procedure is very well explained in react-apollo docs in section: Computing from props 这个过程在react-apollo文档的“ react-apollo 计算”一节中有很好的解释

Based on your example and your requirements, I made a demo which is hosted on codesandbox and uses GraphQL API. 根据您的示例和您的要求,我制作了一个代码,该代码托管在codesandbox上并使用GraphQL API。

Demo: https://codesandbox.io/embed/PNnjBPmV2 演示: https//codesandbox.io/embed/PNnjBPmV2

Data.js

import React from 'react';
import PropTypes from 'prop-types';
import gql from 'graphql-tag';
import { graphql } from 'react-apollo';

const Data = ({ data }) =>
  <div>
    <h2>Data</h2>
    <pre style={{ textAlign: 'left' }}>
      {JSON.stringify(data, undefined, 2)}
    </pre>
  </div>;

Data.propTypes = {
  active: PropTypes.bool.isRequired,
};

const query = gql`
  query SearchAuthor($id: Int!) {
    author(id: $id) {
      id
      firstName
      lastName
    }
  }
`;

export default graphql(query, {
  options(ownProps) {
    return {
      variables: {
        // This is the place where you can 
        // access your component's props and provide
        // variables for your query
        id: ownProps.active ? 1 : 2,
      },
    };
  },
})(Data);

App.js

import React, { Component } from 'react';
import Data from './Data';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      active: false,
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange() {
    this.setState(prevState => ({
      active: !prevState.active,
    }));
  }

  render() {
    const { active } = this.state;

    return (
      <div>
        <h1>App</h1>
        <div>
          <label>
            <input
              type="checkbox"
              checked={active}
              onChange={this.handleChange}
            />
            If selected, fetch author <strong>id: 1</strong>
          </label>
        </div>
        <Data active={active} />
      </div>
    );
  }
}

export default App;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM