簡體   English   中英

React Apollo:從Component狀態動態更新GraphQL查詢

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

我有一個組件,使用react-apollo裝飾器語法顯示GraphQL查詢的結果。 查詢接受一個參數,我想根據組件狀態動態設置該參數。

請考慮以下簡化示例:

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

單擊復選框時,我想重新提交查詢,根據復選框的狀態動態設置myQueryactive屬性。 為簡潔起見,我省略了復選框的處理程序和綁定,但是如何在狀態更改時重新提交查詢?

創建一個將有一個新的組件prop 主動從父組件傳遞。

這個過程在react-apollo文檔的“ react-apollo 計算”一節中有很好的解釋

根據您的示例和您的要求,我制作了一個代碼,該代碼托管在codesandbox上並使用GraphQL API。

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