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

如何在Apollo查询组件中返回Highcharts?

  •  0
  • Peterhack  · 技术社区  · 6 年前

    我正在尝试返回Highchart中的graphql数据。不知怎么的,它没有被显示出来。观看现场演示 here .

    import React from "react";
    import { Query } from "react-apollo";
    import Highcharts from "highcharts";
    
    import { ExchangeRates, client } from "./query";
    
    class OtherComponentTest extends React.Component {
      componentDidMount() {
        <Query query={ExchangeRates} client={client}>
          {({ loading, error, data }) => {
            if (error) return <h1>Error...</h1>;
            if (loading || !data) return <h1>Loading...</h1>;
    
            return Highcharts.chart("production", {
              ...
            });
          }}
        </Query>;
      }
      render() {
        return (
          <div>
            <div id="production">loading </div>
          </div>
        );
      }
    }
    
    export default OtherComponentTest;
    

    1 回复  |  直到 6 年前
        1
  •  0
  •   Daniel Rearden    6 年前

    您不能像那样将JSX添加到componentDidMount方法中并期望它做些什么。您的代码将被传输到 React.createElement 但是元素本身永远不会被渲染。有两种不同的方法可以解决这个问题:

    第一,为highcharts容器创建一个包装器组件。

    // elsewhere...
    class HighchartsComponent extends React.Component {
      componentDidMount () {
        Highcharts.chart("production", {
          series: this.props.series,
          // other config
        })
      }
    
      render () {
        return <div id="production">loading</div>
      }
    }
    
    // inside whatever render method
    <Query query={ExchangeRates} client={client}>
      {({ loading, error, data }) => {
        if (error) return <h1>Error...</h1>;
        if (loading || !data) return <h1>Loading...</h1>;
    
        return <HighchartsComponent series={data.someQuery.someField}/>
      }}
    </Query>
    

    ApolloConsumer withApollo 特别 直接访问Apollo客户端实例。内部 componentDidMount query 方法并使用结果。比如:

    const { data } = await this.props.client.query({ query: ExchangeRates })
    if (data && data.someQuery) {
      Highcharts.chart("production", {
        series: data.someQuery.someField,
        // other config
      })
    }
    

    official library

    import Highcharts from 'highcharts'
    import HighchartsReact from 'highcharts-react-official'
    
    <Query query={ExchangeRates} client={client}>
      {({ loading, error, data }) => {
        if (error) return <h1>Error...</h1>;
        if (loading || !data) return <h1>Loading...</h1>;
    
        return (
          <HighchartsReact
            // your props here
          />
        )
      }}
    </Query>