【问题标题】:react-apollo - how to set query variables from wrapped component?react-apollo - 如何从包装组件设置查询变量?
【发布时间】:2017-07-11 11:21:39
【问题描述】:

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

<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 for MyComponent 看起来像

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

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

【问题讨论】:

  • 使用 graphcool 我无法让过滤器工作,指出不能将对象作为子对象传递等。关于从那里去哪里的任何想法?

标签: reactjs react-apollo apollo-client


【解决方案1】:

您可以将 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() 处理使用新参数的任何后续重新获取。

【讨论】:

  • 我有一个类似query getItems($filter: JSON!) { items(filter: $filter) { id } }的查询。 filter 不可为空。所以第一个请求,应该有有效的变量filterMyComponentWithData 没有任何道具,props .myParentParam 不适合这里。
  • 那么你打算从哪里获取第一个过滤器值?它必须来自父母,或者必须硬编码,这是您唯一的选择。这意味着您应该通过options.variables 设置它。
  • 我已经更新了上面的代码示例以更好地说明该方法。 ParentComponentChildComponent 提供初始默认过滤器值,之后ChildComponent 可以在必要时使用不同的参数重新获取。或者,过滤器值也可以存储在ParentComponent 的状态中,通过将updateFilter(filter) 方法传递给ChildComponent,您可以从那里对其进行操作。
  • 似乎来自ParentComponent 的变量只是react-apollo 的一种方式。谢谢你的回答。
【解决方案2】:

refetch 接受 variables 对象作为参数,请参阅 documentation

【讨论】:

  • 是的,但在 refetch 将被传递给包装组件之前,react-apollo 获取带有“无效”变量的查询。我需要带有来自包装组件的变量的第一个请求。不是第二个。
猜你喜欢
  • 2018-06-27
  • 2020-02-19
  • 2017-07-21
  • 2020-02-28
  • 2019-02-02
  • 2018-09-25
  • 2019-01-26
  • 2017-04-22
  • 2011-04-27
相关资源
最近更新 更多