2017-02-21 68 views
3

react-apollo提供转换组件的道具来查询变量的能力: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); 

UPDATE

QUERYMyComponent看起来像

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

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

+0

使用graphcool我无法获得过滤器的工作,说明一个不能传递对象作为孩子等。任何想法从哪里去? –

回答

1

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

+0

是的,但在'refetch'将被传递给包装组件之前,react-apollo会使用“无效”变量提取查询。我需要第一个请求来自包装组件的变量。不是第二。 –

4

您可以通过父道具到初始的变量取在graphql特定的,就像这样:

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()处理参数。

+1

我有一个类似于查询getItems($ filter:JSON!){items(filter:$ filter){id}}'的查询。 'filter'是**不可为空**。所以firt请求,应该有有效的变量'filter'。 'MyComponentWithData'没有任何道具,'props .myParentParam'在这里不适合。 –

+1

然后,您打算获得第一个过滤器值?它必须来自父母,或者必须进行硬编码,这是您唯一的选择。这意味着你应该通过'options.variables'来设置它。 – pleunv

+0

我已经更新了上面的代码示例以更好地说明该方法。 'ParentComponent'用最初的默认过滤器值提供'ChildComponent',之后'ChildComponent'可以在需要时用不同的参数重新获取。 或者,过滤器值也可以存储在ParentComponent的状态中,并通过将'updateFilter(filter)'方法传递给'ChildComponent',您可以从那里操作它。 – pleunv