4

react-apollo提供将组件道具转换为查询变量的能力:

<MyComponentWithData propsForQueryVariables={...} />

但我需要使用包装组件中的变量开始查询。

就像是:

class MyComponent extends React.Component {
   //...
   onReady() {
     // should be first request to server
     this.props.refetch({
       // variables here
     })
   }

   onFilterChanged() {
     this.props.refetch({
       // new variables here
     })
   }
}

const MyComponentWithData = graphql(QUERY, {
  options: {
    waitUntilComponentStartQuery: true
    // pollInterval:...
  },
  props({ data: { items, refetch } }) {
    return {
      items: items,
      refetch: refetch
    };
  }
})(MyComponent);

更新

QUERY看起来MyComponent

query getItems($filter: JSON!) {
 items(filter: $filter) {
  id
  name
 } 
}

filter不可为。所以第一个请求应该有有效的变量filter,并且这个变量应该在包装的组件中创建。

4

2 回答 2

4

您可以将 parent props 传递给 graphql HoC 中初始 fetch 的变量,如下所示:

ParentComponent.jsx

import ChildComponent from './ChildComponent';

const ParentComponent = () => <ChildComponent filterPropValue="myDefaultFilterValue" />;

export default ParentComponent;

ChildComponent.jsx

class ChildComponent extends React.Component {
  refresh() {
    this.props.refetch({
      filter: 'mynewFilterValue'
    });
  }

  render() {
    return (
      <div>I am a child component with {this.props.items.length} items.</div>
    );
  }
}

export default graphql(MyQuery, {
  options: (props) => ({
    variables: {
      filter: props.filterPropValue
    }
  }),
  props: ({ data: { items, error, refetch }) => ({
    items,
    error,
    refetch
  })
})(ChildComponent);

然后可以通过处理任何带有新参数的后续重新获取refetch()

于 2017-02-22T09:38:12.267 回答
1

refetch接受一个variables对象作为参数,请参阅文档

于 2017-02-21T20:39:07.967 回答