2017-02-21 5 views
3

react-apollo 변수를 쿼리 구성 요소 소품을 변환 할 수있는 기능을 제공합니다. 같은react-apollo - 래핑 된 구성 요소에서 쿼리 변수를 설정하는 방법?</p> <pre><code><MyComponentWithData propsForQueryVariables={...} /> </code></pre> <p>하지만 포장 구성 요소에서 변수 쿼리를 시작해야합니다

뭔가 :

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

filter이 Null을 허용하지 입니다

처럼

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 MyComponent에 대한

QUERY 보인다. 따라서 첫 번째 요청에는 유효한 변수 filter이 있어야하며이 변수는 래핑 된 구성 요소에 만들어야합니다.

+0

graphcool을 사용하여 필터를 작동시킬 수 없으며 개체를 어린이 등으로 전달할 수 없다고 명시되어 있습니다. 거기에서 어디로 가야하는지에 대한 아이디어가 있습니까? –

답변

1

refetchvariables 개체를 인수로 받아들입니다 (documentation 참조). 초기의 변수에 부모 소품을 통과 할 수

+0

예,하지만 'refetch'가 래핑 된 구성 요소로 전달되기 전에 'invalid'변수가 포함 된 react-apollo 페치 쿼리가 발생합니다. 래핑 된 구성 요소의 변수가있는 첫 번째 요청이 필요합니다. 두 번째가 아닙니다. –

4

이처럼 graphql HOC에서 가져 오기 : 새와

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); 

이후의 refetches 매개 변수는 refetch()을 통해 처리 할 수 ​​있습니다.

+1

'query getItems ($ filter : JSON!) {items (filter : $ filter) {id}}'와 같은 쿼리가 있습니다. 'filter'는 ** null을 허용하지 않습니다 **. 그래서 firt 요청은 유효한 변수'filter'를 가져야합니다. 'MyComponentWithData'는 어떤 소품도 가지지 않고'props.myParentParam'는 여기에 적합하지 않습니다. –

+1

그러면 첫 번째 필터 값은 어디에서 얻을 계획입니까? 그것은 부모로부터 온 것이거나, 하드 코딩되어야하며, 그것들은 당신의 유일한 선택 사항입니다. 이는'options.variables'를 통해 설정해야 함을 의미합니다. – pleunv

+0

접근 방식을 더 잘 보여주기 위해 위의 코드 예제를 업데이트했습니다. 'ParentComponent'는'ChildComponent'에 초기 기본 필터 값을 공급합니다. 그 후'ChildComponent'는 필요하다면 다른 매개 변수로 다시 패치 할 수 있습니다. 또한 필터 값은'ParentComponent'의 상태에 저장 될 수 있으며'updateFilter (filter)'메소드를'ChildComponent'에 전달하여 거기에서 조작 할 수 있습니다. – pleunv