2017-05-30 13 views
3

有谁知道向apollo添加查询变量的正确方法是如何从反应中获得的?如果手动添加图书名称字符串而不是传入$name查询变量,我可以使用以下代码来工作,但只要我添加该图书并尝试将名称变量通过propTypes中的选项传入,即Invariant Violation: The operation 'data' wrapping 'BookPage' is expecting a variable: 'name' but it was not found in the props passed to 'Apollo(BookPage)'如何将graphQL查询变量传递到装饰反应组件

我直接从reactQL包中获得装饰器的语法,所以我知道它比其他示例有更多的语法糖,但它对于查询仍然有效吗?

const query = gql` 
    query ($name: String!){ 
    bookByName(name: $name) { 
     id 
    } 
} 
`; 

@graphql(query) 
class BookPage extends React.PureComponent { 
    static propTypes = { 
    options: (props) => { return { variables: { name: "Quantum Mechanics"}}}, 
    data: mergeData({ 
     book: 
     PropTypes.shape({ 
      id: PropTypes.string.isRequired, 
     }), 
    }), 
    } 

    render() { 
    const { data } = this.props; 
    if (data.loading) { 
     return <p>Loading</p> 
    } 
    const { bookByName } = data; 
    const book = bookByName; 

    return (
     <p>book.id</p> 
    ); 
    } 
} 

export default BookPage; 

回答

4

@graphql修饰器有第二个参数,您可以在其中定义Query或Mutation的选项。

config中的选项定义类似。

所以你的情况可能是这样的:

const query = gql` 
 
    query ($name: String!){ 
 
    bookByName(name: $name) { 
 
     id 
 
    } 
 
} 
 
`; 
 

 
@graphql(query, { 
 
    options: (ownProps) => ({ 
 
    variables: { 
 
     name: ownProps.bookName // ownProps are the props that are added from the parent component 
 
    }, 
 
    })}) 
 
class BookPage extends React.PureComponent { 
 
    static propTypes = { 
 
    bookName: PropTypes.string.isRequired, 
 
    data: mergeData({ 
 
     book: 
 
     PropTypes.shape({ 
 
      id: PropTypes.string.isRequired, 
 
     }), 
 
    }), 
 
    } 
 

 
    render() { 
 
    const { data } = this.props; 
 
    if (data.loading) { 
 
     return <p>Loading</p> 
 
    } 
 
    const { bookByName } = data; 
 
    const book = bookByName; 
 

 
    return (
 
     <p>book.id</p> 
 
    ); 
 
    } 
 
} 
 

 
export default BookPage;

+0

我试图把该选项配置到propTypes,而不是装饰,用自己的方式伟大的工作。谢谢! – Coherent

相关问题