代码之家  ›  专栏  ›  技术社区  ›  duncanhall

React-Apollo:从组件状态动态更新GraphQL查询

  •  11
  • duncanhall  · 技术社区  · 9 年前

    我有一个组件,它使用 react-apollo

    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>;
        }
    }
    

    单击复选框后,我想重新提交查询,动态设置 active 中的属性 myQuery ,基于复选框的状态。为了简洁起见,我省略了复选框的处理程序和绑定,但是如何在状态更改时重新提交查询?

    1 回复  |  直到 9 年前
        1
  •  14
  •   Dawid Karabin    9 年前

    创建一个新组件,该组件将具有 prop 忙碌的

    这一过程在 react-apollo 第节中的文档: Computing from props

    演示: 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;