有谁知道向apollo添加查询变量的正确方法是什么?如果我手动添加书名字符串而不是传入$name
查询变量,我可以得到以下代码,但是只要我添加它并尝试通过propTypes中的选项传递name变量,Invariant Violation: The operation 'data' wrapping 'BookPage' is expecting a variable: 'name' but it was not found in the props passed to 'Apollo(BookPage)'
我直接从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;
答案 0 :(得分:4)
@graphql
装饰器有第二个参数,您可以在其中定义查询或变异的选项。
与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;
&#13;