2017-02-21 22 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